Recent Changes - Search:

Basics

Languages

Tools

OS

Resources

PmWiki

pmwiki.org

edit SideBar

Loops

Basic structure

for i in range ; do
   action
done

where range is a string containing the tokens to be acted upon. This makes Bash loops potentially very powerful since they can act on pretty much anything.

You can have a mundane loop:

for i in 1 2 3 4 5 ; do
   echo $i
done
-> 1
-> 2
-> 3
-> 4
-> 5

where if you want a larger sequence, you should see the seq function.

The freedom in defining the range and the capability of Bash to act on strings instead of just numbers allows you to act on files (at your own risk!):

for i in $( ls *.out ); do
   mv $i output/
done

Note: This can be achieved with a simple mv *.out output/, but more complex operations can be performed in the loop than by using *.

Single line

for i in range ; do action ; done

Using variables in a loop

for i in `seq 1 5`; do
   j[$i]=$(($i+1))
   echo ${j[$i]}
done
-> 2
-> 3
-> 4
-> 5
-> 6

Here we first access the value of i by using $i, then add 1 to it through integer arithmetic with $(($i+1)) and assign that to the ith element of j with j[$i]. In order to get the value back out of j, we need a slightly more complicated syntax, ${j[$i]} so that Bash recognizes what we want, instead of $j[$i] which would just print the value of i between square brackets since j itself does not have a value, only elements of j do.

While loops

You can also make loops which execute as long as a certain condition is respected:

while Condition; do Something; done

which is especially useful to make infinite loops by using true as the condition, then putting it in background by following done with $.

Loop control

Much like many other languages, Bash allows you to:

break
Exit a loop before its completion
continue
Immediately move on to the next iteration in the loop
Edit - History - Print - Recent Changes - Search
Page last modified on May 10, 2016, at 07:24 PM