如何在shell脚本的变量中存储命令? [英] How to store a command in a variable in a shell script?
本文介绍了如何在shell脚本的变量中存储命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在一个变量中存储一个以后要使用的命令(不是命令的输出,而是命令本身)
I would like to store a command to use at a later period in a variable (not the output of the command, but the command itself)
我有一个简单的脚本如下:
I have a simple script as follows:
command="ls";
echo "Command: $command"; #Output is: Command: ls
b=`$command`;
echo $b; #Output is: public_html REV test... (command worked successfully)
然而,当我尝试更复杂的东西时,它失败了.例如,如果我使
However, when I try something a bit more complicated, it fails. For example, if I make
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
知道如何将这样的命令(带有管道/多个命令)存储在变量中以备后用吗?
Any idea how I could store such a command (with pipes/multiple commands) in a variable for later use?
推荐答案
使用 eval:
x="ls | wc"
eval "$x"
y=$(eval "$x")
echo "$y"
这篇关于如何在shell脚本的变量中存储命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文