Bash:For
lastmod 2024-07-27created 2015-10-1613 edits
A summary of how to use the for statement in bash.
Numeric ranges
You can list the numbers to iterate over as follows.
Or you can give a range as follows,
Or you can change the increment as follows.
There is also a command-line tool called seq that does something similar.
Example
Applying TDD, code that runs a test N times until it fails is as follows.
File list loop
You can list files as follows.
Or you can give a wildcard as follows.
Commend output loop
Array loop
python-style foreach loop:
c-style for loop:
PLANETS=( "EARTH" "MARS" "VINUS" )
for (( i=0; i<${#PLANETS[@]}; i++ )); do
echo "Planet #$i is ${PLANETS[i]}"
done
Text input loop
Reads a file and then runs a LOOP based on its list.
Changing the input field separator
Assume the following file exists.
(There is a TAB character in the middle.)
In this case, a regular Text input loop uses both tabs (\t) and newlines as separators. If you want to use only newlines, not tabs, as separators, modify the IFS variable as follows.
find result loop
If the results found with the find command contain spaces, you cannot use it like this:
So you should use it as follows.
Three-expression bash for loops syntax
Rename example
A script that renames files in the order of the found INDEX is as follows.
DIR=directory_name
NAMES=`find $DIR -iname '*.jpg'`
val=0
for i in $NAMES; do
mv "$i" "$DIR/$val.jpg"
let "val = val + 1"
done