26.算术扩展 使用expr命令和$((...))是等价的,但是expr要慢很多。
使用$((...))如下(注意结果的不同):
$x=10 $x=10
$x=$x+1 $x=$(($x+1))
$echo $x $echo $x
10+1 11
思考其与$(...)的区别
27.参数扩展 编写script来处理名为1_tmp 和 2_tmp的两文件如下:
#!/bin/sh #!/bin/sh
for i in 1 2 for i in 1 2
do do
my_secret_process $i_tmp my_secret_process ${i}_tmp
done done
左边是有错误的,右边 ${i}_tmp 才是正确形式。
Parameter Expansion Description
${param:-default} If param is null, set it to the value of default.
${#param} Gives the length of param.
${param%word} From the end, removes the smallest part of param that matches
word and returns the rest.
${param%%word} From the end, removes the longest part of param that matches
word and returns the rest.
${param#word} From the beginning, removes the smallest part of param that
matches word and returns the rest.
${param##word} From the beginning, removes the longest part of param that
matches word and returns the rest.
举例分析如下:
#!/bin/sh
unset foo
echo ${foo:-bar} 结果是 bar
foo=fud
echo ${foo:-bar} 结果是 fud
foo=/usr/bin/X11/startx
echo ${foo#*/} 从左边起,寻找第一个/,输出右边剩下的字符串
echo ${foo##*/} 从左边起,寻找最后一个/,输出右边剩下的字符串
bar=/usr/local/etc/local/networks
echo ${bar%local*} 从右边起,寻找第一个local,输出左边剩下的字符串
echo ${bar%%local*} 从右边起,寻找最后一个local,输出左边剩下的字符串
exit 0
运行后的结果是:
bar
fud
usr/bin/X11/startx
startx
/usr/local/etc
/usr
28.内部文档/嵌入文档Here documents
嵌入文档以"<<"符号开头,其后紧跟一个特殊的字符序列,该序列将在文档末尾再次出现,以告知shell嵌入文档完了。如:
cat <<!FUNKY!
hello
this is a here
document
!FUNKY!