💾 Archived View for rawtext.club › ~s0kx › pure-sh-bible › loops.gmi captured on 2022-03-01 at 15:18:10. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2021-12-03)
-=-=-=-=-=-=-
Alternative to seq and only suitable for small and static number ranges. The number list can also be replaced with a list of words, variables etc.
# Loop from 0-10. for i in 0 1 2 3 4 5 6 7 8 9 10; do printf '%s\n' "$i" done
Alternative to seq.
# Loop from var-var. start=0 end=50 while [ "$start" -le "$end" ]; do printf '%s\n' "$start" start=$((start+1)) done
while IFS= read -r line || [ -n "$line" ]; do printf '%s\n' "$line" done < "file"
Don’t use ls.
CAVEAT: When the glob does not match anything (empty directory or no matching files) the variable will contain the unexpanded glob. To avoid working on unexpanded globs check the existence of the file contained in the variable using the appropriate file conditional. Be aware that symbolic links are resolved.
# Greedy example. for file in *; do [ -e "$file" ] || [ -L "$file" ] || continue printf '%s\n' "$file" done # PNG files in dir. for file in ~/Pictures/*.png; do [ -f "$file" ] || continue printf '%s\n' "$file" done # Iterate over directories. for dir in ~/Downloads/*/; do [ -d "$dir" ] || continue printf '%s\n' "$dir" done