1.变量可以直接存储单个命令
变量可以直接存储单个命令,运行如下:
tmp="ls -l"
>>$tmp
结果:
-rw-rw-r-- 1 root root 290 Dec 6 12:03 Makefile
-rw-r--r-- 1 root root 2000 Jan 12 2021 README.md
-rw-rw-r-- 1 root root 528 Dec 10 02:23 goorm.manifest
-rw-r--r-- 1 root root 22 Nov 13 2020 index.py
-rw-rw-r-- 1 root root 0 Dec 17 12:26 ls.log
-rw-rw-r-- 1 root root 29 Nov 18 06:20 test.log
-rwxr-xr-x 1 root root 133 Nov 17 12:09 test.sh
但是无法存储多个命令和包含管道处理的命令
tmp="pwd;ls"
echo $tmp
>>pwd;ls
$tmp
bash: pwd;ls: command not found
tmp="pwd|tee cmd.log"
echo $tmp
>>pwd|tee cmd.log
$tmp
>>bash: pwd|tee: command not found
此时比较笨的办法是将多个命令的变量$tmp 按命令拆开
tmp="pwd|ls -l"
cmd0=$(echo $tmp|cut -d '|' -f 1)
cmd1=$(echo $tmp|cut -d '|' -f 2)
>>echo $cmd0
pwd
>>echo $cmd1
ls -l
分别运行cmd0和cmd1得到
>> $cmd0;$cmd1
>>/workspace/nst3
>>total 24
-rw-rw-r-- 1 root root 290 Dec 6 12:03 Makefile
-rw-r--r-- 1 root root 2000 Jan 12 2021 README.md
-rw-rw-r-- 1 root root 528 Dec 10 02:23 goorm.manifest
-rw-r--r-- 1 root root 22 Nov 13 2020 index.py
-rw-rw-r-- 1 root root 0 Dec 17 12:26 ls.log
-rw-rw-r-- 1 root root 29 Nov 18 06:20 test.log
-rwxr-xr-x 1 root root 133 Nov 17 12:09 test.sh
2.使用eval命令(推荐使用)
tmp="pwd|ls -l"
>>eval $tmp
/workspace/nst3
-rw-rw-r-- 1 root root 290 Dec 6 12:03 Makefile
-rw-r--r-- 1 root root 2000 Jan 12 2021 README.md
-rw-rw-r-- 1 root root 528 Dec 10 02:23 goorm.manifest
-rw-r--r-- 1 root root 22 Nov 13 2020 index.py
-rw-rw-r-- 1 root root 0 Dec 17 12:26 ls.log
-rw-rw-r-- 1 root root 29 Nov 18 06:20 test.log
-rwxr-xr-x 1 root root 133 Nov 17 12:09 test.sh
在Shell脚本中,eval
是一个内置命令,用于将字符串作为命令行重新解释并执行。这使得你能够动态构建命令或执行由变量组成的复杂命令。