Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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='/path/to/some/command'

$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

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

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
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 '13 at 3:37

2 Answers 2

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:

mycommand=/path/to/some/command

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

These lines below worked for me under bash:

mycommand=/usr/bin/find
$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 '13 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). –  Stéphane Chazelas Apr 9 '13 at 6:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.