loop over files, numbers and lists
Repeat commands for every file of a kind, a range of numbers, or the items of an array.
Steps
-
for f in *.jpg; do echo "$f"; doneevery .jpg here
-
for i in {1..10}; do echo "$i"; done1 to 10
-
for ((i = 0; i < n; i++)); do echo "$i"; donea range in variables
-
for x in "${list[@]}"; do echo "$x"; doneevery item of an array
-
find . -name '*.log' -print0 | while IFS= read -r -d '' f; do gzip "$f"; doneevery file under here, any name
-
seq 1 2 101, 3, 5, 7, 9: numbers for other commands
Notes
- {1..$n} does not work: braces come before variables; use the (( )) form.
Commands used
seqfind
Each has a page in lore: lore seq opens it.
Related recipes
- ask for input in a scriptAsk yes or no, read a password without showing it, or wait for an answer with a time limit.
- check if a file or folder existsTest in a script whether a path exists, is a file, a folder, empty or runnable.
- check if a string contains a textTest in a script whether a string contains, starts with or matches something.
- find the script's own folderInside a script, find the folder the script is in, to reach files next to it.