一. 用{命令}在本shell执行语句
[root@ansible9 ~]# a=1;b=1
[root@ansible9 ~]# { a=2;b=3;cd test;touch 1.txt; }
[root@ansible9 test]# cd ..
[root@ansible9 ~]# echo $a;echo $b;ll ./1.txt;ll test/1.txt
2
3
ls: cannot access './1.txt': No such file or directory
-rw-r--r-- 1 root root 0 Dec 30 11:26 test/1.txt
格式:{空格语句1;语句2;空格}
二. 用(命令)在子shell执行语句
[root@ansible9 ~]# a=1;b=1
[root@ansible9 ~]# (a=2;b=3;cd test;touch 1.txt)
[root@ansible9 ~]# echo $a;echo $b;ll ./1.txt;ll test/1.txt
1
1
ls: cannot access './1.txt': No such file or directory
-rw-r--r-- 1 root root 0 Dec 30 11:29 test/1.txt
格式:(语句1;语句2)
三. $(命令)在子shell执行语句
[root@ansible9 ~]# a=1
[root@ansible9 ~]# b=`a=2;cd test;touch 123.txt`
[root@ansible9 ~]# echo $a
1
[root@ansible9 ~]# ll ./123.txt
ls: cannot access './123.txt': No such file or directory
[root@ansible9 ~]# ll test/123.txt
-rw-r--r-- 1 root root 0 Dec 30 11:34 test/123.txt
[root@ansible9 ~]# a=1
[root@ansible9 ~]# $(a=100;cd test;touch wo.txt)
[root@ansible9 ~]# echo $a
1
[root@ansible9 ~]# ll ./wo.txt
ls: cannot access './wo.txt': No such file or directory
[root@ansible9 ~]# ll test/wo.txt
-rw-r--r-- 1 root root 0 Dec 30 11:38 test/wo.txt
四. 变量名=$(命令)变量名只能获得命令的标准输出,不能获得标准错误输出除非重定向标准错误输出到标准输出
[root@ansible9 ~]# a=0
[root@ansible9 ~]# a=`222`
bash: 222: command not found...
[root@ansible9 ~]# echo $a
[root@ansible9 ~]# a=`ls`
[root@ansible9 ~]# echo $a
anaconda-ks.cfg backup_gitlab.sh Desktop Documents Downloads initial-setup-ks.cfg Music Pictures Public Templates test Videos
[root@ansible9 ~]#
[root@ansible9 ~]# a=0
[root@ansible9 ~]# a=`222 2>&1`
[root@ansible9 ~]# echo $a
bash: 222: command not found...
[root@ansible9 ~]#