$()
$()和反引号``都是用来做命令替换用的,对一串命令重新开一个子shell进行执行
[root@zabbix scripts]# echo "the last sunday is $(date -d"last monday" +%Y-%m-%d)"
the last sunday is 2021-03-15
-
$()的优势
在很多情况下反引号``和单引号’'容易混淆 -
( ) 不 足 ‘ ‘ 基 本 上 可 在 全 部 的 u n i x s h e l l 中 使 用 , 若 写 成 s h e l l s c r i p t 移 植 性 比 较 高 。 而 ( )不足 ` `基本上可在全部的unix shell中使用,若写成shell script移植性比较高。而 ()不足‘‘基本上可在全部的unixshell中使用,若写成shellscript移植性比较高。而( )并不是每一种shell都能使用。
${}
${ }用来作变量替换
一般情况下,$var与${var}作用相同。但是用${ }会比较精确的界定变量名称的范围
[root@zabbix scripts]# name=tye
[root@zabbix scripts]# echo ${name}
tye
[root@zabbix scripts]# echo $name
tye
#下面例子中$AB则系统会认识是AB变量,而不是$A的值和B的值的结合
[root@zabbix scripts]# A=B
[root@zabbix scripts]# echo $AB
[root@zabbix scripts]# echo ${A}B
BB
${}特殊用法
#定义一个变量files
[root@zabbix scripts]# files=/root/scripts/copycmd.sh
#获取第一个/右边的所有字符串信息
[root@zabbix scripts]# echo ${files#*/}
root/scripts/copycmd.sh
#获取最后一个/右边的字符串信息
[root@zabbix scripts]# echo ${files##*/}
copycmd.sh
#获取最后一个/左边的字符串信息
[root@zabbix scripts]# echo ${files%/*}
/root/scripts
#获取第一个/左边的字符串信息
[root@zabbix scripts]# echo ${files%%/*}
(空值)
#注:%-去除右边获取左边的字符串信息,#-去除左边获取右边的字符串信息
#提取从第1个字符开始向后取4个字符
[root@zabbix scripts]# echo ${files:1:4}
root
[root@zabbix scripts]# echo ${files:6:7}
scripts
# ${var/dir/path}实现字符串替换,将dir替换为path
[root@zabbix scripts]# echo ${files/copycmd.sh/copylog.txt}
/root/scripts/copylog.txt
# ${var//dir/path}实现字符串替换,将所有dir替换为path
[root@zabbix scripts]# echo ${testpath//path/abc}
/abc1/abc2/abc3/abctest.txt
#获取files的长度,单位为字节
[root@zabbix scripts]# echo ${#files}
24