Monday, January 31, 2011

BASH : For loop

touch forloop.sh
CONTENT of FILE
#!/bin/bash
#for arg in [list]; do action item done
for country in USA Uganda Germania
do
echo $country
done
#END


3 ways to run a file
1.  source ./forloop.sh -> print all 3 countrys
2. . forloop.sh
3. ./forloop.sh


. forloop.sh | sort -> sort in alfabetical order
. forloop.sh | sort > country.txt -> redirect the output into file
cp forloop.sh forloop2.sh
CONTENT of FILE
#!/bin/bash
for file in 'ls -A'
do
echo $file
done
#END
. forloop2.sh -> prints all the files from the current direcotry
CONTENT of FILE
#!/bin/bash
DIR="/etc"
for file in 'ls -A $DIR'
do
echo $file
done
#END
. forloop2.sh -> prints the file from /etc folder
. forloop2.sh | wc -l -> prints the numbers of files from /etc folder


cp forloop2.sh forloop3.sh
pico forloop3.sh
CONTENT of FILE
#!/bin/bash
for num in 'seq 1 100'
do
echo $num
done
#END
Results -> create numbers from 1 to 100
cp forloop3.sh forloop4.sh
pico forloop4.sh
CONTENT of FILE
#!/bin/bash
for user in 'cat /etc/passwd'
do
echo $user
done
#END
The results are unreadable


pico forloop4.sh
CONTENT of FILE
#!/bin/bash
DIR="/etc/passwd"
COUNT=0
for user in `cat $DIR | cut -f 1 -d ':'`
do
echo $user
let "COUNT += 1" # increment Count
done
echo There are $COUNT users registered
exit 0
#END
->returns the users from /etc/passwd
cat /etc/passwd | wc -l -> return the number of users

No comments:

Post a Comment