Escaping whitespace inside nested shell / perl scripts

I am trying to run a perl script from a bash script (I will change this design later, but carry with me for now). bash script gets an argument to run. The script argument looks like this:

test.sh "myscript.pl -g \"Some Example\" -n 1 -p 45"

      

in a bash script, I just run the argument that was passed:

#!/bin/sh

$1

      

However, in my perl script, the -g argument only gets "Some

(this is with quotes) instead Some Example

. Even if I quote this, it gets disconnected due to spaces.

I tried to avoid whitespace but it doesn't work ... any ideas?

+2


source to share


4 answers


To run it as posted test.sh "myscript.pl -g \"Some Example\" -n 1 -p 45"

, follow these steps:

#!/bin/bash
eval "$1"

      

This causes the argument to $1

be processed by the shell, so the individual words are split and the quotes removed.



Or, if you want, you can remove the quotes and run test.sh myscript.pl -g "Some Example" -n 1 -p 45

if you changed your script to:

#!/bin/bash
"$@"

      

"$@"

is replaced with all arguments $1

, $2

etc., as passed on the command line.

+2


source


Quotes are usually handled by a parser that doesn't see them when you substitute a value $1

into your script.

You may have more luck:

#!/bin/sh
eval "$1"

      

which gives:



$ sh test.sh 'perl -le "for (@ARGV) { print; }" "hello world" bye'  
hello world
bye

      

Note that simply making the shell interpret the quoting with "$1"

will not work, because then it tries to treat the first argument (i.e. the entire command) as the name of the command to be executed. You need to go through eval

to get the correct quote and then re-parse the command.

This approach is (obviously?) Dangerous and fraught with security risks.

+1


source


I would suggest that you specify the perl script in a separate word, then you can specify the parameters when accessing them, and it is still easy to extract the script name without requiring the shell to strip the words, which is the main problem you are having.

test.sh myscript.pl "-g \"Some Example\" -n 1 -p 45"

      

and then

#!/bin/sh
$1 "$2"

      

+1


source


if you really need to do this (for whatever reason) why not just do:

sh test.sh "'Example" -n 1 -p 45 "

in: test.sh

RUN = myscript.pl
echo `$ RUN $ 1

(there must be backward backward signals `before $ RUN and after $ 1)

0


source







All Articles