Regrettably, you will have to use eval
if you want to keep the redirection operators in the string value.
Like other shell-special characters, redirection operators are only evaluated if they are not quoted. When you expand the JAVACMD parameter it will split on whitespace, but it will not re-evaluate any special characters it includes. Using eval
forces this re-evaluation.
The problem with eval
is it forces every character be re-evaluated. In your case, none of the other characters will have any untoward affects. If your string value contained some other shell-special character (e.g. ;(){}
…) that you did not want the shell to re-evaluate you would have to escape/quote it inside the string value so that eval
would not give it a special meaning.
⋮
eval "$JAVACMD &"
To avoid problems with eval
, I suggest moving the redirection out of the string value:
JAVACMD="… program.jar"
⋮
$JAVACMD >log 2>&1 &
Done this way the only characters in the string value that you need to watch out for are the whitespace characters (e.g. if you needed some embedded whitespace in one of the options/arguments; if you run into this you might consider using an array variable or "$@"
(a singular, array-like variable available in all Bourne-like shells)).