Below are examples of the Bash for loop in action. If you need more help, see the official Bash documentation for an introduction to Bash programming.
Examples
Echo all jpg files in the current folder:
for JPG in *.jpg; do
echo $JPG
done
Count a list of numbers:
for NUM in $(seq 1 10); do
echo $NUM
done
One liners work as well:
for n in $(seq 3); do echo $n; done
Iterate through the process ID's for httpd and kill them:
for PID in $(ps -C httpd | awk '/httpd/ { print $1 }'); do
kill -TERM $PID
done
List arguments to a function named showarg:
showarg() {
for ARG in $@; do
echo $ARG
done
}
Loop through folders and back them up using tar:
DATE=$(date +'%Y-%m-%d')
for DIR in /etc /var /root; do
tar -czvf /backups/$DIR_$DATE.tgz $DIR
done