示例:防止变量无值
# path="/var/log" find ${path:-/tmp} -type f -name "*.tar.gz" -exec rm -f {} \; # 当/var/log目录不存在时,删除/tmp目录下的内容,主要是防止/var/log目录不存在时会将root或者根删除${value:=word}
若变量未定义或者值为空时,在返回word的值的同时,将word赋给value
注:变量替换的值也可以是``括起来的命令:$USERDIR={$Mydir:-pwd}
${value:?word}
[root@centos8 script]#test="xufengnian" [root@centos8 script]#result=${test:?UNSET} [root@centos8 script]#echo $result xufengnian [root@centos8 script]#echo $test xufengnian [root@centos8 script]#${value:+word}
[root@centos8 script]#test="xufengnian" [root@centos8 script]#result=${test:+UNSET} [root@centos8 script]#echo $result UNSET [root@centos8 script]#echo $test xufengnian [root@centos8 script]# 3. 查找并删除 # 从变量$string开头开始删除最短匹配$substring子串 ${string#substring} [root@centos8 script]#str="I am xufengnian I am" [root@centos8 script]#echo ${str#I am} xufengnian I am [root@centos8 script]# # 从变量$string开头开始删除最长匹配$substring子串 ${string##substring} [root@centos8 script]#str="I am xufengnian I am" [root@centos8 script]#echo ${str##I am} xufengnian I am [root@centos8 script]# # 从变量$string结尾开始删除最短匹配$substring子串 ${string%substring} [root@centos8 script]#str="I am xufengian I am" [root@centos8 script]#echo ${str%I am} I am xufengian [root@centos8 script]# # 从变量$string结尾开始删除最长匹配$substring子串 ${string%%substring} [root@centos8 script]#str="I am xufengnian I am" [root@centos8 script]#echo ${str%%I am} I am xufengnian [root@centos8 script]# # 删除var表示的字符串中第一次被pattern匹配到的字符串 ${var/pattern} [root@centos8 script]#str="I am xufengnian I am" [root@centos8 script]#echo ${str/I am} xufengnian I am [root@centos8 script]# # 删除var表示的字符串中所有被pattern匹配到的字符串 ${var//pattern} [root@centos8 script]#str="I am xufengnian I am" [root@centos8 script]#echo ${str//I am} xufengnian [root@centos8 script]#示例:把下面所有系统中文件的文件名的finished内容去掉
touch 1_finished.jpg 2_finished.jpg 3_finished.jpg 4_finished.jpg 5_finished.jpg # 方法一: for file in `ls *.jpg` do mv $file ${file%finished*}.jpg done # 方法二: ls *.jpg|awk -F "finished" '{print "mv " $0,$1""$2}'|bash # 方法三: rename "finished" "" *.jpg 4. 字符大小写转换 # 把var中的所有小写字母转换为大写 ${var^^} # 把var中的所有大写字母转换为小写 ${var,,}