Shell Script Tutorial
Logic - FOR
Example 1 :
for i in 1 2 3 4 5; do
echo "Welcome $i times"
done
Resuit:
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times
Example 2 :
for i in `cat /tmp/shadow`; do
id=`echo $i | cut -d ':' -f1,1`
echo ""
echo "[$id] password is changed"
echo -e "123456\n123456\n" | passwd $id
done
This scripts is used to changed password for mass linux account.
Example 3 :
for (( i = 0; i <= 5; i++ )); do
echo "Welcome $i times"
done
Resuit:
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times
Example 4:
for (( i = 1; i <= 5; i++ )); do ### Outer for loop ###
for (( j = 1 ; j <= 5; j++ )); do ### Inner for loop ###
echo -n "$i "
done
echo "" #### print the new line for break ###
done
This is nesting of FOR loop, Resuit:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
Example 5:
for (( i = 1; i <= 9; i++ )); do ### Outer for loop ###
for (( j = 1 ; j <= 9; j++ )); do ### Inner for loop ###
tot=`expr $i + $j`
tmp=`expr $tot % 2`
if [ $tmp -eq 0 ]; then
echo -e -n "\033[47m "
else
echo -e -n "\033[40m "
fi
done
echo -e -n "\033[40m" #### set back background colour to black
echo "" #### print the new line ###
done
This chess-board will be printed with this nesting of FOR loop.
Example 6:
f1="/tmp/word1.txt"
f2="/tmp/word2.txt"
for i in `cat $f1`; do
for j in `cat $f2`; do
if [ $i = $j ]; then
echo $i
fi
done
done
This script is designed to get the same word/line compare between with 2 files.
Example 7:
IFS=$'\n'
for i in `cat /tmp/log`; do
echo $i
done
For loop to count each line without white space problem

Server is hosted by Alanstudio
Linux Operating System
Recommend screen resolution 1024 x 768 / IE / FireFox
Alan Studio © 2007 by Alan Cheung Hin Lun. All rights reserved.
|