只是做一些记录,方便回头翻阅
1:``(反引号),$(),$(())
反引号与$():两者都是在脚本中执行命令时使用,建议使用$()。
原因很简单:$(),不易混淆,反引号就不说了,不熟悉的人看都看不出来吧。
不过$(),存在兼容性问题,可能跟版本有关,不过一般都没什么问题了。
example:`ls -al | wc -l` $(ls -al | wc -l)
可以嵌套使用,比如 $(command1 $(command2))。
$(()):做算数运算用
example:
a=1;b=2
$((a+b)) 与$((${a}+${b})) 等价 均为3
可以做不同进制数的运算,只是输出结果均为10进制
example:
echo $((16#2a))值为42
2:${}
引用变量使用。
${VAR1} 与 $VAR1 没有区别。
推荐前者,还是规范一点比较好。
${}还有字符串截取功能,参考了网上的记忆方法(很形象的说),请注意键盘上# $ %的位置。
example:
file=/dir1/dir2/my.file.txt
${file#*/}-------dir1/dir2/my.file.txt
${file##*/}--------my.file.txt
${file%/*}-------/dir1/dir2
${file%%/*}-----空
记忆方法:
#是去掉左边 %是去掉右边 单个符号是最小匹配 两个符号是最大匹配
以下就是普通的截取了
${file:0:5} ------/dir1
${file:5:5}-------/dir2
很容易明白了吧
还可以做字符串替换
${file/dir/path} ------ /path1/dir2/my.file.txt
${file//dir/path} ----- /path1/path2/my.file.txt
前面是单一替换 后边是全部替换 差距就在一个斜杠。
${#var} 可以计算变量长度
3:数组的一些
a=(a b c def)
${a[@] ${a[*]} ---- a b c def 输出所有数组元素
${#a[@]} ${#a[*]} ----- 4 输出数组元素数量
${#a[3]} ---- 3 输出第三个元素的长度
${a[@]:0} ----- 输出a b c def
${a[@]:1:2} ---- 输出 b c
子串替换
array=([0]=one [1]=two [2]=three [3]=four)
${array[@]#t*e} ----输出one two e four 左边开始最短匹配
${array[@]##t*e} --- 输出one two four 左边开始最长匹配
${array[@]%*o}-----输出one tw three four 右边开始最短匹配
${array[@]%%*o}------输出one three four 右边开始最长匹配
${array[@] /o/m} ----- 输出mne twm three fmur 第一个匹配到的会替换
${array[@] //o/m}------输出mne twm three fmur 所有匹配到的都会被删除(这个例子不太合适)
${array[@] //o/} ----输出 ne tw three fur 没有指定替换的子串 则删除
${array[@] /#thr/k} ---输出one two kee four 匹配字符串前端子串
${array[@] /#o*/k} ---输出 k two three four
${array[@] /%our/k} --- 输出one two three fk 匹配字符串后端子串
${array[@] /%*r/k} ---- 输出one two three k
可以看到 数组的一些匹配操作都是对数组中的每一个元素而言的