| Home Profile Fun |
#112 Linux 03.04.2007
For loops as one-liners and within shell scriptsThe syntax is different for bash and csh. The following examples are written for the bash. You find csh examples in the FreeBSD articles. Find out the shell type you get when logging into the system. echo $SHELLNote that if you change the shell during a session by typing bash or csh etc. this environment variable does not get updated. So it may not reflect your current shell, just the login-shell. The login-shell can be changed by editing /etc/passwd. For loops can be used as one-liners from the command line or within shell scripts. We start with examples for the command line. Print alle records of test.txt for i in `cat test.txt`; do echo $i; done Print the name of all files inside /tmp which end with .txt for i in `find /tmp -name "*.txt"`; do echo $i; done Just print a list of letters for i in a b c; do echo $i; done Also nested loops can be run from the shell prompt. This example finds all files in the current working directory which end with .txt. Then it prints the content of each of these files. for i in *.txt; do for ii in `cat $i`; do echo $ii; done; done Another way is to create the parameter list by using a variable. export VARTEST="a b c" for i in $VARTEST; do echo $i ; done The next one-liner does a little bit more within the for loop. I wrote this once when I needed the first mx record of a long list of domains. First the command gets the content of domains.txt which is just a list of domain names. Then it uses dig to get the first mx record for each domain. The head and awk commands clean up the output by removing unneeded lines and columns. for i in `cat domains.txt`; do dig $i mx +short | head -n1 | awk '{print $2}'; done
Within shell scripts the syntax is more clear of course. It looks like this: for i in `cat test.txt` do echo $i done By default the parameter list of for loops is being split at blanks, tabs and new-lines. But it is possible to change this behaviour with the internal field separator. |