For Loop

The For Loop
If you want to repeat a task more than one time, then you will be interested in loops.  A loop will provide a way for you to perform that task with just one set of code. It is designed to execute a finite number of times on a list of items.  Whenever the for command is used it is followed by a variable, then the word “in” and a list of words.  At that point the first word is moved into the position of the variable and when the command is run, the commands between the “do” and “done” it is removed from the list of words.  Once all of the words have been removed from the list the script moves beyond the “done”.

Lesson 11 | Lesson 13

The For Loop has this structure:

for variable in list
do

done


#!/bin/sh
for i in 10 20 30 40 50 60 70 80 90
do
echo “Counting by 10s.....number $i”
done


Here is an example of a script that creates four empty log files and then does a grep to see if they were all created.  The file command is used to test the file and then classify it.  In this case they are classified correctly as empty files.  The For Loop continues through all the files that are logs until it is complete.

#!/bin/sh
touch log.1 log.2 log.3 log.4
for files in `ls | grep log`
do
echo "file: `file $files`"
done


daily_bk.sh
This script will create a daily backup directory and copy all modified files within 24 hours into that directory.

#!/bin/bash

TIMESTAMP=`date +%Y%m%d_%H%M%S`;
echo $TIMESTAMP
DIR=/home/daily_$TIMESTAMP;
mkdir $DIR
for SCRIPT in `find /root/scripts -iname '*.sh' -mtime -1`
do
if [ -f $SCRIPT ]
then
cp $SCRIPT $DIR/

echo "$SCRIPT is backed up to $DIR"
fi
done



These two lines provide a way to create a directory based upon a timestamp so that each directory is different, creating the ability to capture multiple versions of the same files as they are developed.  TIMESTAMP is a variable used throughout the script.

TIMESTAMP=`date +%Y%m%d_%H%M%S`;
echo $TIMESTAMP


These two lines take the timestamp and create the actual directory.  DIR becomes a variable.

DIR=/home/daily_$TIMESTAMP;
mkdir $DIR



The for loop evaluates all files, case insensitive(-iname), which end in ".sh" and have been modified within one day (-mtime -1).

for SCRIPT in `find /root/scripts -iname '*.sh' -mtime -1`

Now the loop will loop through the list of files and copy those that qualify into the directory with the timestamp.  As they copied over as message lists the ones that have been copied.

do
if [ -f $SCRIPT ]
then
cp $SCRIPT $DIR/

echo "$SCRIPT is backed up to $DIR"
fi
done

 


Copyright CyberMontana Inc. and BeginLinux.com
All rights reserved. Cannot be reproduced without written permission. Box 1262 Trout Creek, MT 59874