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

查看:48
本文介绍了如何将命令存储在 shell 脚本的变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个变量(不是命令的输出,而是命令本身)中存储一个以后要使用的命令.

I would like to store a command to use at a later time 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

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

How could I 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天全站免登陆