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

Manu
  • 13

1 Answers1

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.

jesse_b
  • 37,005