2

Lets suppose that I have a folder named white space that contains a class file called foo.

On the command line, I can easily call the foo program by the following command on the

java -cp "white space/" foo

and it would work fine.

I want to set this entire command as a variable in Bash and call this variable rather than the whole command itself.

So, lets say I set the command into the following

bar='java -cp "white space/" foo'

I tried calling the command by doing $bar, but I keep getting an error saying:

Error: Could not find or load main class space

How would you resolve this?

mtber75
  • 938
  • 1
  • 8
  • 15
  • Can you escape char in bash like you would in java? so it would look something like this: `bar="java -cp \"white space/\" foo"`? – Rabbit Guy Apr 26 '16 at 18:07
  • How about presenting the actual code that fails for you? We cannot really answer without seeing how you are trying to *use* `$bar`. In other words, present a [mcve]. – John Bollinger Apr 26 '16 at 18:08
  • Note, too, that the `/` is not actually part of the directory name. It would be better to omit it. – John Bollinger Apr 26 '16 at 18:09

2 Answers2

2

Don't use variables to store entire command lines, precisely because you can't accommodate whitespace. Use an array, preferably to hold just the options and specify the command separately.

options=(-cp "white space/" foo)
java "${options[@]}"

or, define a function:

bar () {
    java -cp "white space/" foo
}
chepner
  • 497,756
  • 71
  • 530
  • 681
1

Things are interpreted differently because parsing an input command and starting an external program with parameters are two different steps done by bash, and part of the first step here is falling through.

The solution is:

eval "$bar"

For further details, see: https://stackoverflow.com/a/11065196/1871033

Community
  • 1
  • 1
CherryDT
  • 25,571
  • 5
  • 49
  • 74