quoting in perl command in shell script

R

rduke15

Hi,

I have a weird problem with this simple bash script calling a Perl
command in a variable. I don't understand what's wrong.

$ cat test.sh

#!/bin/sh
set -x
cmd="perl -e 'print 1+2'"
$cmd

$ ./test.sh

+ cmd=perl -e 'print 1+2'
+ perl -e 'print 1+2'
Can't find string terminator "'" anywhere before EOF at -e line 1.


I also tried all sorts of variations with the quotes, but nothing seems
to work.

Thanks for any help...
 
B

Barry Margolin

rduke15 said:
Hi,

I have a weird problem with this simple bash script calling a Perl
command in a variable. I don't understand what's wrong.

$ cat test.sh

#!/bin/sh
set -x
cmd="perl -e 'print 1+2'"
$cmd

$ ./test.sh

+ cmd=perl -e 'print 1+2'
+ perl -e 'print 1+2'
Can't find string terminator "'" anywhere before EOF at -e line 1.


I also tried all sorts of variations with the quotes, but nothing seems
to work.

Try: eval $cmd
 
S

Stephane CHAZELAS

2004-05-24, 09:19(+00), Anno Siegel:
Stephane CHAZELAS said:
2004-05-21, 15:26(-04), Barry Margolin:
[...]
cmd="perl -e 'print 1+2'"
$cmd [...]
Try: eval $cmd

Please get used to:

eval "$cmd"

Why?

Because, in Bourne like shells, an unquoted variable is a list
of file patterns not a string (it's fixed in zsh).

If a variable is not quoted, upon expansion, it is splitted
according to the value of the IFS special parameter, and any
wildcards are expanded.

For instance,

cmd="echo 'a b'"
eval $cmd

outputs "a b", because $cmd is splitted into "echo", "'a" and
"b'". eval concatenates those with spaces, so runs:

echo 'a b'

You would think:

cmd='echo "*"'
eval $cmd

harmless?

Try it after:

touch './""; rm -rf "$HOME"'

(DON'T!)
 
S

Stephane CHAZELAS

2004-05-24, 09:31(+00), Ben Morrow:
[...]
Shell, not Perl. Presumably its more portable.

No, it's because

eval $cmd
in shell, would be the equivalent of perl's:

eval(join(" ", map(glob, split($IFS_regexp, $cmd))))

IT'S ALMOST ALWAYS WRONG TO LEAVE A VARIABLE UNQUOTED IN SHELL
SCRIPTS.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top