1

I'm facing some strange behabiour in my bash script.

I have a simple script parser.sh, wich is really simple:

#!/bin/bash

for arg in "$@"
do 
    echo ARGUMENT: "$arg"
done

This script is called from another script in the same directory, lets call this one test.sh

#!/bin/bash

`pwd`/parser.sh "ARG1=FIRST" "ARG2=TESTING SPACES"

The script shown above really works, and outputs the arguments as expected:

ARGUMENT: ARG1=FIRST
ARGUMENT: ARG2=TESTING SPACES

However, if I change the test.sh as follows:

#!/bin/bash

ARGS="\"ARG1=FIRST\" \"ARG2=TESTING SPACES\""
`pwd`/parser.sh $ARGS 

This simple modification, makes the code to fails when iterating over arguments:

ARGUMENT: "ARG1=FIRST"
ARGUMENT: "ARG2=TESTING
ARGUMENT: SPACES"

Why is that happening? What am I missing?

Thanks in advance

3
4

Don't save your arguments in a regular variable, use an array:

args=( "ARG1=FIRST" "ARG2=TESTING SPACES" )
./parser.sh "${args[@]}"

Your quotes are being treated literally since they are escaped and your variable is being expanded without quotes so it is subject to word splitting.

Additionally there is no need to use pwd like that, . can be used to refer to the present directory.

You can see how your variable is being treated with the following:

$ ARGS="\"ARG1=FIRST\" \"ARG2=TESTING SPACES\""
$ printf '%q\n' $ARGS
\"ARG1=FIRST\"
\"ARG2=TESTING
SPACES\"

As you see the double quotes are expanding escaped which was not your intent, and the whitespace between TESTING and SPACES is not escaped.

4
  • Thanks so much for your help
    – Manu
    Jan 8 at 13:13
  • One last question, I agree that it's a bad practise, but, why is happening that? I mean, I'm slipping away all the special characters, right?
    – Manu
    Jan 8 at 13:19
  • @Manu: I have edited my answer
    – jesse_b
    Jan 8 at 13:23
  • Thanks again, really apreciate it!
    – Manu
    Jan 8 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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