1

Invoking a shell script with command line arguments containing spaces is generally solved by enclosing the argument in quotes:

getParams.sh 'one two' 'foo bar'

Produces:

one two
foo bar

getParams.sh:

while [[ $# > 0 ]]
do
    echo $1
    shift
done

However, if a shell variable is first defined to hold the value of the arguments such as:

args="'one two' 'foo bar'"

then why does:

getParams.sh $args

not recognize the single quotes enclosing the grouped arguments? The output is:

'one
two'
'three
four'

How can I store command line arguments containing spaces into a variable so that when getParams is invoked, the arguments are grouped according to the quoted arguments just as in the original example?

2

1 Answer 1

2

Use an array:

args=('one two' 'foo bar')

getParams.sh "${args[@]}"

Using args="'one two' 'foo bar'" wont work, because the single quotes retain their literal value when inside double quotes.

To preserve multiple spaces in the arguments (and also handle special characters such as *), you should quote your variable:

while [[ $# -gt 0 ]]
do
    echo "$1"
    shift
done
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, @user000001. That mostly works. The remaining problem is that multiple spaces are replaced with one space. How do I preserve all the spaces if some strings have multiple adjacent spaces embedded?
@tgoneil: You should quote the variable ("$1") to preserve multiple whitespaces in echo.
Ah ha! That did the trick! Thank you @user000001!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.