说明:
双圆括号结构与let命令很相似,((...))结构允许算术扩展和赋值,举个简单的例子,a=$((5+3)),将把变量"a" 设为"5+3",或者8,
然而,双圆括号结构也被认为是在bash中使用C语言风格变量操作的一种处理机制。
1.C语言风格的变量操作
#! /bin/sh
echo
(( a = 23 ))
echo "a ((initial value) = $a"
(( a++ ))
echo "a (after a++) = $a"
(( a-- ))
echo "a (after a--) = $a"
(( ++a ))
echo "a (after ++a) = $a"
(( --a ))
echo "a (after --a) = $a"
echo
n=1;let --n && echo "True" || echo "False"
n=1;let n-- && echo "True" || echo "False"
echo
(( t = a<45?7:11 ))
echo "If a < 45,then t=7,else t=11."
echo "t = $t "
echo
exit 0
2.每个[list]元素中都带有两个参数的for循环
#! /bin/sh
for planet in "Mercury 36" "Venus 67" "Earth 93" "Mars 142" "Jupiter 483"
do
set -- $planet ----------解析变量"planet",并且设置位置参数,其中"--"将防止$planet为空,或者以一个破折号开头
echo "$1 $2,000,000 miles from sun"
done
exit 0
3.对包含在变量中的文件列表进行操作
#! /bin/sh
FILES="/usr/sbin/accept
/usr/sbin/pwck
/usr/sbin/chroot
/usr/bin/fakefile
/usr/badblocks
/sbin/ypbind"
echo
for file in $FILES
do
if [ ! -e "$file" ]
then
echo "$file does not exist."
echo
continue
fi
ls -l $file | awk '{ print $9 " file size: " $5 }'
whatis `basename $file`
echo
done
exit 0
4.在for循环中操作文件
#! /bin/sh
echo
for file in *
do
ls -l "$file"
done
echo;echo
for file in *.conf
do
rm -f $file
echo "Removed file /"$file/""
done
echo
exit 0
5.使用命令替换来产生for循环的[list]
#! /bin/sh
NUMBERS="9 7 3 8 37.53"
for i in "$NUMBERS"
do
echo -n $i
done
echo
exit 0
6.对于二进制文件的grep替换
#! /bin/sh
E_BADARGS=65
E_NOFILE=66
if [ $# -ne 2 ]
then
echo "Uage: `basename $0` search_string filename"
exit $E_BADARGS
fi
if [ ! -f "$2" ]
then
echo "File /"$2/" does not exists."
exit $E_NOFILE
fi
IFS=$'/012' ---------等同于'/n'
for word in $( strings "$2" | grep "$1" )
do
echo $word
done
exit 0