1

This is a generic question since the "problem" has arisen a number of times and I have never been able to get around it, and I wonder if it is in fact just not possible.

The matter concerns BOURNE shell scripts (not Bash) and whether it is possible to use environmental variables whose values contain strings which include spaces.

So consider a simple case to illustrate the issue --

#! /bin/sh

parameters='-T "XXX YYY ZZZ"'

/usr/bin/xterm ${parameters}

exit 0

When the script is run, the internal quotes are interpreted as literal characters and not as string delimiters.

sh -x test

+ parameters=-T "XXX YYY ZZZ"
+ /usr/bin/xterm -T "XXX YYY"
/usr/bin/xterm: No absolute path found for shell: YYY"

xterm is seeing -T "XXX as the title parameter and YYY" as the next parameter for which shell to use.

I have tried reversing the order of nesting of the quotes, backslashes, even removing the quotes and just using backslashes on the spaces, viz

sh -x test

+ parameters=-T XXX\ YYY
+ /usr/bin/xterm -T XXX\ YYY\
/usr/bin/xterm: No absolute path found for shell: YYY\

but nothing works.

If the title string does not contain a space, then there is no problem eg

#! /bin/sh

parameters='-T "the_title"'

/usr/bin/xterm ${parameters}

One reason I would like to get this to work if possible is to use the variable as a parameter to a shell script function, otherwise it is going to mean multiple parameters. In this case it would mean one for the command line flag (-T) and one for the command line parameter value (the title string).

So is it possible to have spaces in the string within the environmental variable to pass as a parameter to an executable or not in BOURNE shell scripts by somehow making the spaces not being treated as command line parameter separators when the variable is expanded?

4

1 回答 1

1

尝试这个:

parameters='-T "XXX YYY ZZZ"'
eval `echo /usr/bin/xterm ${parameters}`

注意那里的反引号。这个成语:

eval `echo ...yadda...`

强制外壳重新解析任何...yadda...就像您键入它一样。

于 2013-07-07T17:36:40.380 回答