Bash implements for, while, and until loops(not discussed).
For Loop
The basic syntax of the for loop is:
for var in list; do
some commands
done
Note the semicolon; it is important to not omit it. The commands are executed once for every item in the list. The current item is accessed through the variable $var, e.g.,
Use VI to edit for.sh
--------------------------------
for i in 1 2 3 4 5 6 7 8 9 10; do
echo -n "$i "
done
echo
--------------------------------
$ chmod 755 for.sh
$ ./for.sh
1 2 3 4 5 6 7 8 9 10
The option -n to echo means do not print a newline character after outputting the text.
Another example,
for i in $(ls); do
echo $i
done
This script display the name of each of the files in the current directory one per output line. Another example,
Use VI to edit ls-dirs.sh
--------------------------------
for i in *; do
if [ -d "$i" ]; then
echo "$i [dir]"
else
echo $i
fi
done
--------------------------------
$ mkdir foo1
$ mkdir foo2
$ chmod 755 ls-dirs.sh
$ alias ls-dirs=./ls-dirs.sh
$ ls
foo1 foo2 for.sh if.sh ls-dirs.sh
$ ls-dirs
foo1 [dir]
foo2 [dir]
The seq command (type man seq for help) can be used to generate an integer sequence. The syntax is, seq first increment last which will generate an integer sequence starting at first, incrementing by increment, and stopping at last. For example, Here is a loop which displays the first 100 odd integers,
for i in `seq 1 2 100`; do
echo -n $i " "
done
Note that the seq command must be enclosed in backquotes `seq…` so the shell will execute it to generate the desired output. This loop prints the first 100 odd integers in reverse order,
for i in `seq 99 -2 1`; do
echo -n $i " "
done
While Loops
The basic syntax of the while loop is,
while [ conditional-expression ]; do
statements
done
I have ommitted examples as the while loop is used in a similar context to the for loop.
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment