Loops for and while && User interfaces

for

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/bin/bash
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done

for i in $( ls ); do
echo item: $i
done

for i in `seq 1 10`;
do
echo $i
done

for i in {1..5}
do
echo "Welcome $i times"
done

for (( c=1; c<=5; c++ ))
do
echo "Welcome $c times..."
done
for i in {0..10..2}
do
echo "Welcome $i times"
done

for i in $(seq 1 2 20)
do
echo "Welcome $i times"
done

单行实例

1
2
3
4
5
6
7
8
9
for ((i=1; $i<=9;i++)); do echo $i; done

for ip in {1..10};do echo $ip; done

for i in `seq 1 10`;do echo $i;done

for ip in {81..92}; do ssh root@172.16.3.$ip date; done

for n in {23..32} {49,50} {81..92}; do mkdir /tmp/$n; echo $n; done

—>backup file

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash
FILES="$@"
for f in $FILES
do
# if .bak backup file exists, read next file
if [ -f ${f}.bak ]
then
echo "Skiping $f file..."
continue # read next file and skip cp command
fi
# we are hear means no backup file exists, just use cp command to copy file
/bin/cp $f $f.bak
done

while

1
2
3
4
5
6
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
		
while read name age
do
echo $name $age
done << EOF
neo 30
jam 31
john 29
EOF


while read name age
do
[[ $age -gt 30 ]] && echo $name
done << EOF
neo 30
jam 31
john 29
EOF
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ cat mount.sh
#!/bin/sh
while read LINE
do

s=`echo $LINE|awk '{print $1}'`
d=`echo $LINE|awk '{print $2}'`

umount -f $d
mount -t nfs4 $s $d

done < mount.conf

$ cat mount.conf
172.16.0.1:/ /www/logs/1
172.16.0.2:/ /www/logs/2
172.16.0.3:/ /www/logs/3
172.16.0.4:/ /www/logs/4
172.16.0.5:/ /www/logs/5

User interfaces

using select to make simple menus:

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash
OPTIONS="Hello Quit"
select opt in $OPTIONS; do
if [ "$opt" = "Quit" ]; then
echo done
exit
elif [ "$opt" = "Hello" ]; then
echo Hello World
else
clear
echo bad option
fi
done

read
input your name in 30s

1
2
3
4
$ read -p "Please input your name: " -t 30 named
Please input your name: neo

$ echo $named