Frederic
Frederic

Reputation: 1820

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. 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?

Upvotes: 1

Views: 92

Answers (1)

anubhava
anubhava

Reputation: 786011

If you want to store full command line to call your function then you should use shell arrays:

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.

Storing full command like in a string variable is error prone esp. when you have whitespaces, quotes etc.

Upvotes: 1

Related Questions