4

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?

4
  • 5
    I'm trying to put a command in a variable, but the complex cases always fail! Commented Sep 3, 2013 at 16:11
  • When you say, ...but from what I can tell, $MY_COMMAND does not execute with $MY_ARGUMENT as an argument., are you speculating or did you run a test that fails? It ($MY_COMMAND $MY_ARGUMENT) actually should work depending upon your context. Commented Sep 3, 2013 at 16:11
  • @mbratch: Yes, I ran it and it did not work as $MY_COMMAND $MY_ARGUMENT, basically the command didn't execute. I suppose I could redirect STDERR to STDOUT and catch the logs. Commented Sep 3, 2013 at 16:14
  • 1
    I did a simple test using that technique and it worked. For example, at the shell prompt, if I set FOO=ls and BAR="*.c", then entering $FOO $BAR lists the .c files in my current directory. So you will need to share the context in which it's being used which is causing it to fail. Commented Sep 3, 2013 at 16:15

2 Answers 2

5

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.
Sign up to request clarification or add additional context in comments.

Comments

3

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.