如何将变量中的空格传递给变量中的命令

时间:2019-09-04 15:03:31

标签: bash

我想将要执行的bash命令放在一个变量中,然后执行该变量。该命令具有参数,并且其中一些参数中可能包含空格。我该怎么办?

到目前为止,我尝试过的事情是这样的:

nbargs(){ echo $#; }          # define some function

command='nbargs 1 "2 3"'      # I want nbargs to recieve 2 args, not 3      

现在,如果一个人直接调用该命令,它将按预期工作。但是间接地,通过变量却没有。

nbargs 1 "2 3"   # output: 2
echo $command    # output: nbargs 1 "2 3"
$command         # output: 3 ???

我该如何解决我的问题,您能解释为什么执行变量时不考虑引号吗?

1 个答案:

答案 0 :(得分:1)

如果要存储完整的命令行来调用函数,则应使用shell数组:

cmd=(nbargs 1 "2 3")

并将其称为:

"${cmd[@]}"

这将正确输出:

2

不要使用变量名command,因为它也是shell实用程序。

像在字符串变量中一样存储完整命令很容易出错。当您有空格,引号等时。