Take the tour ×

This question already has an answer here:

I am trying to run a statement where the name of the command is in a variable. For example:


$my_command -f foo -b bar -s something else 

But the above does not work. I get errors that suggest that the shell is trying to interpret my arguments as commands.

How can I do this in Bash and Zsh?

share|improve this question
Always post specifics. In cases like this, the exact code being used. If not possible, create a functional example. Also provide the exact error output. There are many specific errors which could fall under a broad explanation like this. –  Patrick Apr 9 at 3:37
add comment

marked as duplicate by jasonwryan, vonbrand, jordanm, manatwork, Chris Down Apr 9 at 7:12


2 Answers

up vote 2 down vote accepted

To store a command, you can use a function:

In any Bourne-like shell but bash:

mycommand() /path/to/some/command some fixed args "$@"
mycommand other args

In bash, you need braces:

mycommand() { /path/to/some/command some fixed args "$@";}

(those braces don't hurt in other shells, so best is to use them when you need to be portable)

If you're a csh junkie, you could also use an alias.

You can use a variable as in:


but remember that in every shell but zsh, you need to quote the expansion:

"$mycommand" its args

If you want to store the command and more than it's 0th argument, you can use arrays in shells that support them (bash and zsh do)

mycommand=(/path/to/some/command some fixed args)
"${mycommand[@]}" some other args

In zsh you can get away with

$mycommand some other args

as long as none of the fixed args are empty.

share|improve this answer
add comment

These lines below worked for me under bash:

$mycommand -type d

your problem maybe originating from "/path/to/some/command" and what it does or try to do. Without seeing the actual thing, it is hard to say.

share|improve this answer
Works fine for me in bash also - with or without single-quotes on the mycommand line and with it called my_command or mycommand. –  Dave C Apr 9 at 1:53
That's zsh syntax. In bash, you need to quote $mycommand, otherwise it's subject to word splitting (for insance if IFS contains any of /usrbinfd characters) and filename generation (not applicable here as there's no wildcard character). –  Stephane Chazelas Apr 9 at 6:41
add comment
