Skip to content
Search

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.

for VARIABLE in 1 2 3 4 5 .. N
do
    command $VARIABLE
done

Or you can give a range as follows,

for i in {1..5}
do
    echo "Welcome $i times"
done

Or you can change the increment as follows.

for i in {0..10..2}; do
    echo "Welcome $i times"
done

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.

for i in {0..1000}; do ./tester --gtest_filter=RenderingLoop* || break; done

File list loop

You can list files as follows.

for VARIABLE in file1 file2 file3
do
    command1 on $VARIABLE
done

Or you can give a wildcard as follows.

for name in /path/to/imagenet/val/*.JPEG; do
    convert -resize 256x256\! $name $name
done

Commend output loop

for OUTPUT in $(Linux-Or-Unix-Command-Here)
do
    command1 on $OUTPUT
done

Array loop

python-style foreach loop:

val=("1" "2" "3")
for i in ${val[@]}; do
    echo $i
done

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.

for req in $(cat requirements.txt); do
    echo $req
done

Changing the input field separator

Assume the following file exists.

TEXT1\tBOAD1
TEXT2\tBOAD2

(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.

IFS=$'\n'    # make newlines the only separator
for req in $(cat requirements.txt); do
    echo $req
done

find result loop

If the results found with the find command contain spaces, you cannot use it like this:

for f in $(find . -iname "*.ttf"); do
    echo $f
done

So you should use it as follows.

find . -iname '*.ttf' | while read f; do
    echo "Processing file: $f"
done

Three-expression bash for loops syntax

for (( c=1; c<=5; c++ ))
do
    echo "Welcome $c times"
    if [[ "$c" == "3" ]]; then
        break
    fi
done

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

See also

Favorite site

author Zer0 sitemap