user2591612
user2591612

Reputation:

Concatenate command string in a shell script

I am maintaining an existing shell script which assigns a command to a variable in side a shell script like:

MY_COMMAND="/bin/command -dosomething"

and then later on down the line it passes an "argument" to $MY_COMMAND by doing this :

MY_ARGUMENT="fubar"

$MY_COMMAND $MY_ARGUMENT

The idea being that $MY_COMMAND is supposed to execute with $MY_ARGUMENT appended.

Now, I am not an expert in shell scripts, but from what I can tell, $MY_COMMAND does not execute with $MY_ARGUMENT as an argument. However, if I do:

MY_ARGUMENT="itworks"
MY_COMMAND="/bin/command -dosomething $MY_ARGUMENT"

It works just fine.

Is it valid syntax to call $MY_COMMAND $MY_ARGUMENT so it executes a shell command inside a shell script with MY_ARGUMENT as the argument?

Upvotes: 4

Views: 11236

Answers (2)

konsolebox
konsolebox

Reputation: 75458

With Bash you could use arrays:

MY_COMMAND=("/bin/command" "-dosomething")  ## Quoting is not necessary sometimes. Just a demo.
MY_ARGUMENTS=("fubar")  ## You can add more.

"${MY_COMMAND[@]}" "${MY_ARGUMENTS[@]}"  ## Execute.

Upvotes: 5

Aleks-Daniel Jakimenko-A.
Aleks-Daniel Jakimenko-A.

Reputation: 10653

It works just the way you expect it to work, but fubar is going to be the second argument ( $2 ) and not $1.
So if you echo arguments in your /bin/command you will get something like this:

echo "$1" # prints '-dosomething'
echo "$2" # prints 'fubar'

Upvotes: 3

Related Questions