如何将命令存储在Shell脚本的变量中? [英] How to store a command in a variable in a shell script?

查看:214
本文介绍了如何将命令存储在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆