0

My problem is when I call my program like this it executes fine.

'/usr/local/bin/My program' -args
#or
/usr/local/bin/My\ program -args

However I want to store the command in a variable to call it from a script. I've tried several things:

> command='/usr/local/bin/My program' -args

> $command
bash: /usr/local/bin/My: No such file or directory

> "$command"
bash: '/usr/local/bin/My program' -args: No such file or directory

What's the correct way to invoke this command when stored in a variable?

Similar questions have been asked a bunch but these solutions haven't worked for me.

How do I use a variable containing a filename with spaces in a bash script?

How can I use a variable that contains a space?

Peter Kapteyn
  • 354
  • 1
  • 13
  • 2
    You could store your command as function: `command () { '/usr/local/bin/my program' -args; }`. But you should really not name your program file with spaces. – dan Nov 30 '21 at 17:17
  • 5
    Use an array rather than a scalar variable. https://stackoverflow.com/a/7454624/1030675 – choroba Nov 30 '21 at 17:18
  • really: "But you should really not name your program file with spaces." (@dan) – cornuz Nov 30 '21 at 17:19
  • 1
    `command='/usr/local/bin/My program' -args` should result in `-args: command not found` message. Are you sure there is no such message? `bash: '/usr/local/bin/My program' -args: No such file or directory` that is odd, it should print `command not found` error. Also, after doing `command='/usr/local/bin/My program' -args` variable `command` should be unset. Could you post _the exact_ code that you are executing? – KamilCuk Nov 30 '21 at 17:40
  • 2
    Variables are really for data, not executable code (or shell syntax); functions are a better option for things like this. See [BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!](http://mywiki.wooledge.org/BashFAQ/050) – Gordon Davisson Nov 30 '21 at 18:39

1 Answers1

1

Use an array.

command=('/usr/local/bin/My program' -args)
"${command[@]}"
Andrej Podzimek
  • 2,409
  • 9
  • 12
  • This will solve the white space problem, but do note that a lot of shell syntax won't work from a variable or array, including: list operators (`; | && || &`), redirection, other variables, and also glob and tilde expansion (unless unquoted). Functions are also specifically designed for this purpose, and have less overhead than arrays. The one advantage of an array is if you need to dynamically set or call specific elements. – dan Dec 01 '21 at 03:54