Shell Script Variable Quoting Problem

Posted by apinstein on Stack Overflow See other posts from Stack Overflow or by apinstein
Published on 2010-01-14T03:05:08Z Indexed on 2010/05/09 14:28 UTC
Read the original article Hit count: 170

Filed under:
|
|

I have an sh script that contains the line

$PHP_COMMAND -r 'echo get_include_path();'

I can not edit this script, but I need the eventual command line to be (equivalent to)

php -d include_path='/path/with spaces/dir' -r 'echo get_include_path();'

How can I achieve this?


Below is a script that demonstrates the problem.

#!/bin/sh

# shell script quoting problem demonstration

# I need to be able to set a shell variable with a command with 
# some options, like so
PHP_COMMAND="php -d 'include_path=/path/with spaces/dir'"
# then use PHP_COMMAND to run something in another script, like this:
$PHP_COMMAND -r 'echo get_include_path();'
# the above fails when executed. However, if you copy/paste the output
# from this line and run it in the CLI, it works!
echo "$PHP_COMMAND -r 'echo get_include_path();'"
php -d include_path='/path/with spaces/dir' -r 'echo get_include_path();'
# what's going on?

# this is also interesting
echo "\n--------------------"

# this works great, but only works if include_path doesn't need quoting
PHP_COMMAND="php -d include_path=/path/to/dir"
echo "$PHP_COMMAND -r 'echo get_include_path();'"
$PHP_COMMAND -r 'echo get_include_path();'

echo "\n--------------------"

# this one doesn't when run in the sh script, but again if you copy/paste 
# the output it does work as expected.
PHP_COMMAND="php -d 'include_path=/path/to/dir'"
echo "$PHP_COMMAND -r 'echo get_include_path();'"
$PHP_COMMAND -r 'echo get_include_path();'

Script also available online: http://gist.github.com/276500

© Stack Overflow or respective owner

Related posts about shell-scripting

Related posts about bash