I feel really reluctant to ask this question as it feels like I must be missing something really obvious. However, I am unable to find existing questions with exactly the same problem.
We have a script that we should not edit, and it is causing a problem in how it is handling arguments that include whitespace. I have reduced the problem to a very simple reproducible case:
First, I created a simple script that just outputs the commandline arguments passed to it:
#!/bin/bash
for i; do
echo $i
done
Then I define an environment variable that will be passed into the commandline
MYOPT="With Space"
Then, and this is the part I am unable to change in our environment, I call the command using the variable as a parameter. Unfortunately, the variable is not quoted in our environment.
./mycommand.sh $MYOPT
The output of this is, as you would expect,
./mycommand.sh $MYOPT
"With
Space"
If you do quote the variable in the above command, it works. This seems to be the generally accepted solution to this problem when looking around at other similar questions.
./mycommand.sh "$MYOPT"
"With Space"
However, as I mentioned, we are unable to change how this script is called.
I tried adding in extra quotes in the environment variable as follows, but this too did not help:
MYOPT="\"With Space\""
./mycommand.sh $MYOPT
"With
Space"
Is there a way of defining this environment variable with spaces such that it can be passed into a script without quoting it in the invocation?
For those who are interested, this problem is presenting itself in our RHEL7 tomcat environment. JAVA_OPTS is set in tomcat.conf and we have -Dparamaters="with spaces". The main control script that comes with Tomcat does not quote these JAVA_OPTS when it calls Java, which leads to this problem. I reduced the problem to the simple example above.
zsh
doesn't do it). Can you fiddle withIFS
without breaking anything? Otherwise, the code that can't be changed must be corrected to use double quotes. – thrig May 09 '17 at 21:20printf -v MYOPT '%q' "With Space"
– iruvar May 09 '17 at 21:31