开发者

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

This has been driving me nuts for hours now.

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 simply prints out the command line arguments given to the script.

For instance:

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

I can give the script a single argument with a space by 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've set up the shell script like this:

#!/bin/bash

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

echo "(command is $COMMAND)"
$COMMAND

I am calling the hello.pl with the same params and escaped quotes. This script returns:

$ ./test.sh 
(command is ./hello.pl "apple pie")
----------------------------------
thanks, you gave me 2 command-line arguments:
"appl开发者_C百科e
pie"

Even though the $COMMAND variable echoes the command exactly like the way I ran the perl script from the command line the second time, this time it does not want to see the apple pie as a single argument.

Why not?


This looks like the problem described in the Bash FAQ as: I'm trying to put a command in a variable, but the complex cases always fail!

The answer to that FAQ suggests a number of possible solutions - I hope that's of use.


The issue of the 2 command-line arguments

"apple
pie"

is due to shell expansion with the IFS shell variable being set to have a space as value.

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

You may use xargs & sh -c '...code...' to mimic / re-enable ordinary parameter parsing.

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

Another option may be to write a few lines of C (like in shebang.c)!

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


You should try eval $COMMAND instead of simply $COMMAND.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜