|
Loops in Bash The command below loops through directories listed in $PATH. $ path=$PATH: $ while [ $path ]; do echo " ${path%%:*} "; path=${path#*:}; done The command below will also loop through directories in your path. $IFS=: $ for dir in $PATH > do > ls -ld $dir > done drwxr-xr-x 2 root root 4096 Jun 10 20:16 /usr/local/bin drwxr-xr-x 2 root root 4096 Jun 13 23:12 /bin drwxr-xr-x 3 root root 40960 Jun 12 08:00 /usr/bin drwxr-xr-x 2 root root 4096 Feb 14 03:12 /usr/X11R6/bin drwxrwxr-x 2 chirico chirico 4096 Jun 6 13:06 /home/chirico/bin Other ways of doing loops: for (( i=1; i <= 20; i++)) do echo -n "$i " done Note, to do it all on one line, do the following: $ for (( i=1; i <= 20; i++)); do echo -n "$i"; done Below, is an example of declaring i an integer so that you do not have to preface with let. $ declare -i i $ i=5; $ while (( $i > 1 )); do > i=i-1 > echo $i > done 4 3 2 You can also use "while [ $i -gt 1 ]; do" in place of "while (( $i > 1 )); do" To get a listing of all declared values $ declare -i Try putting a few words in the file "test" $ while read filename; do echo "- $filename "; done < test |nl -w1 Or, using an array declare -a Array Array[0]="zero" Array[1]="one" Array[2]="two" for i in `seq ${#Array[@]}` do echo $Array[$i-1] done
|