5

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:
"apple
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?

3 Answers 3

6

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.

2

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.