gpt4 book ai didi

linux - 如何将命令存储在 shell 脚本的变量中?

转载 作者:太空宇宙 更新时间:2023-11-04 05:45:40 25 4
gpt4 key购买 nike

我想将命令存储在变量中以便稍后使用(不是命令的输出,而是命令本身)。

我有一个简单的脚本如下:

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

如何将这样的命令(带有管道/多个命令)存储在变量中以供以后使用?

最佳答案

使用评估:

x="ls | wc"
eval "$x"
y=$(eval "$x")
echo "$y"

关于linux - 如何将命令存储在 shell 脚本的变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60372526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com