3

I have two shell scripts. One script dynamically creates the call to the second script, based on the parameter it received, and then executes the call.

My problem is that the parameters the first script gets may contain spaces, so I must quote the parameter in the call to script2.

This is an example to the problem:

script1.sh:

#!/bin/sh
param=$1
command="./script2.sh \"$param\""
echo $command
$command

script2.sh:

#!/bin/sh
param=$1
echo "the value of param is $param"

When I run:

./script1.sh "value with spaces"

I get:

./script2.sh "value with spaces"
the value of param is "value

Which is of course not what I need.

What is wrong here??

TIA.

EDIT :

I found the solution thanks to the useful link in tripleee's comment. Here it is in case it helps anybody.

In short, in order to solve this, one should use an array for the arguments.

script1.sh:

#!/bin/sh
param=$1

args=("$param")
script_name="./script2.sh"
echo $script_name "${args[@]}"
$script_name "${args[@]}"

1 Answer 1

1

Use "$@" to refer to all command-line parameters with quoting intact.

Sign up to request clarification or add additional context in comments.

2 Comments

where should I use it? I tried param="$@" but it didn't solve the problem
Use it directly, assigning to a named variable is problematic. sh -x ./script2 "$@" if you want to echo the command as well - this is problematic for related reasons. See also mywiki.wooledge.org/BashFAQ/050

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.