Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

unix

perl

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?

like image 621
Symen Timmermans Avatar asked Mar 04 '11 13:03

Symen Timmermans


1 Answers

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.

like image 77
Mark Longair Avatar answered Nov 15 '22 03:11

Mark Longair