Handling Perl command line arguments with spaces from a bash script?

It made me go for hours.

Consider the following test script in perl: (Hello.pl)

#!/usr/bin/perl
print "----------------------------------\n";
$numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments:\n";

foreach $argnum (0 .. $#ARGV) {
    print "$ARGV[$argnum]\n";
}

Ok, it just prints the command line arguments specified in the script.

For instance:

$ ./hello.pl apple pie
----------------------------------
thanks, you gave me 2 command-line arguments:
apple
pie

I can give the script one argument with a space, surrounding the words with double quotes:

$ ./hello.pl "apple pie"
----------------------------------
thanks, you gave me 1 command-line arguments:
apple pie

Now I want to use this script in a shell script. I installed the shell script as follows:

#!/bin/bash

PARAM="apple pie"
COMMAND="./hello.pl \"$PARAM\""

echo "(command is $COMMAND)"
$COMMAND

I call hello.pl with the same parameters and escaped quotes. This script returns:

$ ./test.sh 
(command is ./hello.pl "apple pie")
----------------------------------
thanks, you gave me 2 command-line arguments:
"apple
pie"

Despite the fact that the $ COMMAND variable echoes the command in the same way as the second time I ran the perl script from the command line, this time it does not want to see the apple pie as one argument.

Why not?

+5
3

, Bash FAQ : , !

FAQ - , .

+6

"apple
pie"

, IFS .

printf '%q\n' "$IFS"   # show value of IFS variable

xargs sh -c '... code...' / .

PARAM="'apple pie'"
printf '%s' "$PARAM" | xargs sh -c './hello.pl "$@"' argv0

C ( shebang.c)!

http://www.semicomplete.com/blog/geekery/shebang-fix.html

+2

eval $COMMAND $COMMAND.

0

All Articles