Bash For Loop Examples(转载)

转载

1
2
3
4
5
6
for VARIABLE in 1 2 3 4 5 .. N
do
command1
command2
commandN
done
1
2
3
4
5
6
for VARIABLE in file1 file2 file3
do
command1 on $VARIABLE
command2
commandN
done
1
2
3
4
5
6
for OUTPUT in $(Linux-Or-Unix-Command-Here)
do
command1 on $OUTPUT
command2 on $OUTPUT
commandN
done
1
2
3
4
5
6
for (( EXP1; EXP2; EXP3 ))
do
command1
command2
command3
done
1
2
3
4
5
#!/bin/bash
for (( c=1; c<=5; c++ ))
do
echo "Welcome $c times"
done
1
2
3
4
5
#infinite loops
for (( ; ; ))
do
echo "infinite loops [ hit CTRL+C to stop]"
done
1
2
3
4
5
6
7
8
9
10
#!/bin/bash
for file in /etc/*
do
if [ "${file}" == "/etc/resolv.conf" ]
then
countNameservers=$(grep -c nameserver /etc/resolv.conf)
echo "Total ${countNameservers} nameservers defined in ${file}"
break
fi
done
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