0

I'd like to store a command line in a variable, and then execute that command line. The problem is, the command line has arguments with spaces in them. If I do

$ x='command "complex argument"'
$ $x

it calls command with "complex and argument". I tried using "$x" thinking it would preserve the argument splittings, but it only tries to execute a program with the file name command "complex argument". I also tried variations of the quotes (' vs ") and using exec, but it didn't help. Any ideas?

Edit: eval "$x" almost works, but if the whitespaces separating arguments are newlines and not spaces, then it treats the lines as separate commands. Edit2: The extra " quotes were too much, and made eval interpret the newlines not as spaces, but as command delimiters. The solutions in the answers all work.


For testing purposes, I define:

$ function args() { while [[ "$1" != "" ]]; do echo arg: $1; shift; done }

This works as expected:

$ args "1 2" 3
arg: 1 2
arg: 3

$ x="arg 4 5 6"
$ $x
arg: 4
arg: 5
arg: 6

This doesnt:

$ x="args \"3 4\" 5"
$ $x
arg: "3
arg: 4"
arg: 5
jdm
  • 9,470
  • 12
  • 58
  • 110

2 Answers2

5

A safe approach is to store your command line in a BASH array:

arr=( command "complex argument" )

Then execute it:

"${arr[@]}"

OR else another approach is to use BASH function:

cmdfunc() {
    command "complex argument" 
}

cmdfunc
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

Another solution is

x='command "complex argument"'
eval $x
SzG
  • 12,333
  • 4
  • 28
  • 41