我希望将一个命令存储在一个变量(不是命令的输出,而是命令本身)中,以便在以后使用。
我有一个简单的脚本,如下所示:
command="ls";
echo "Command: $command"; #Output is: Command: ls
b=`$command`;
echo $b; #Output is: public_html REV test... (command worked successfully)
然而,当我尝试一些更复杂的东西时,它失败了。例如,如果我制作了
command="ls | grep -c '^'";
输出为:
Command: ls | grep -c '^'
ls: cannot access |: No such file or directory
ls: cannot access grep: No such file or directory
ls: cannot access '^': No such file or directory
我如何将这样的命令(带有管道/多个命令)存储在一个变量中,以供以后使用?
发布于 2011-04-11 08:38:22
使用eval:
x="ls | wc"
eval "$x"
y=$(eval "$x")
echo "$y"
发布于 2019-09-19 13:57:54
对于bash,像这样存储您的命令:
command="ls | grep -c '^'"
像这样运行您的命令:
echo $command | bash
发布于 2022-01-10 06:41:21
不知道为什么这么多答案会让问题变得复杂!使用alias
命令'string to execute‘示例:
alias dir='ls -l'
./dir
[pretty list of files]
https://stackoverflow.com/questions/5615717
复制相似问题