简体   繁体   English

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

[英]How to pass spaces in arguments to a command in a variable

I want to put a bash command to be executed in a variable, and then execute that variable.我想将要执行的 bash 命令放在一个变量中,然后执行该变量。 The command has arguments, and some of those arguments might include spaces in them.命令有参数,其中一些参数可能包含空格。 How can I do that?我怎样才能做到这一点?

What I have tried so far is something like this:到目前为止我尝试过的是这样的:

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

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

Now if one invoke the command directly, it works as expected.现在,如果直接调用该命令,它会按预期工作。 But indirectly, through the variable, it doesn't.但间接地,通过变量,它没有。

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

How can I solve my problem and can you explain why executing the variable does not take into account the quotes?我怎样才能解决我的问题,你能解释为什么执行变量不考虑引号吗?

If you want to store full command line to call your function then you should use shell arrays:如果你想存储完整的命令行来调用你的函数,那么你应该使用 shell 数组:

cmd=(nbargs 1 "2 3")

and call it as:并将其称为:

"${cmd[@]}"

This will correctly output:这将正确输出:

2

Don't use variable name command as that is also a shell utility.不要使用变量名command ,因为它也是一个 shell 实用程序。

Storing full command like in a string variable is error prone esp.像在字符串变量中一样存储完整的命令很容易出错,尤其是。 when you have whitespaces, quotes etc.当您有空格、引号等时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM