Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


2 Answers

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.
like image 75
konsolebox Avatar answered Oct 23 '25 21:10

konsolebox


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'
like image 45
Aleks-Daniel Jakimenko-A. Avatar answered Oct 23 '25 20:10

Aleks-Daniel Jakimenko-A.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!