for x in listif [ $condition1 ] && [ $condition2 ]
# То же самое, что: if [ $condition1 -a $condition2 ]
# Возвращает true если оба операнда condition1 и condition2 истинны...
if [[ $condition1 && $condition2 ]]
do
...
done
for ((a=1,b=1;a<10;a++,b++))
do
...
done
((a = 1, LIMIT = 10))
while (( a <= LIMIT ))
do
echo -n "$a "
((a += 1)) # let "a+=1"
done
while [ condition ]
do
var0=`expr $var0 + 1`
# можно var0=$(($var0+1))
done
Чтение строк из файла
while read a
do
echo $a
done < filelist.txt
until [ condition ]
do
...
done
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done
for i in {1..5}
do
echo "Welcome $i times"
done
# Начиная с 4 версии - можно указывать шаг цикла
echo "Bash version ${BASH_VERSION}..."
for i in {0..10..2}
do
echo "Welcome $i times"
done
# Бесконечный цикл в bash
for (( ; ; ))
do
echo "infinite loops [ hit CTRL+C to stop]"
done
# Выход из цикла
for I in 1 2 3 4 5
do
statements1
statements2
if (disaster-condition)
then
break
fi
statements3
done
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
for I in 1 2 3 4 5
do
statements1
statements2
if (condition)
then
continue
fi
statements3
done
FILES="$@"
for f in $FILES
do
if [ -f ${f}.bak ]
then
echo "Skiping $f file..."
continue
fi
/bin/cp $f $f.bak
done
Посчитать сколько строк в каждом файле
for file in *; do echo $file: `cat $file |wc -l` ; done
Переименовать группу файлов по порядку
$ ls
IMG_0918.JPG IMG_0925.JPG IMG_0931.JPG IMG_0940.JPG
IMG_0922.JPG IMG_0926.JPG IMG_0932.JPG IMG_0945.JPG
IMG_0923.JPG IMG_0927.JPG IMG_0938.JPG IMG_0946.JPG
IMG_0924.JPG IMG_0930.JPG IMG_0939.JPG IMG_0947.JPG
$ for i in *.JPG; do let j+=1 ; mv $i img_$j.jpg ; done
$ ls
img_1.jpg img_13.jpg img_2.jpg img_6.jpg
img_10.jpg img_14.jpg img_3.jpg img_7.jpg
img_11.jpg img_15.jpg img_4.jpg img_8.jpg
img_12.jpg img_16.jpg img_5.jpg img_9.jpg
Работаем с потоком ввода
while read line
do
echo "- $line - "
done
Источники:
- 1-6 - user.su
- 7-14 - www.cyberciti.biz
- 16 - www.netadmintools.com
- 17 - tldp.org