Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quote parameters when calling a shell script from within another script using a variable

Tags:

shell

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[@]}"
like image 513
Dikla Avatar asked Mar 13 '26 13:03

Dikla


1 Answers

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

like image 176
tripleee Avatar answered Mar 16 '26 12:03

tripleee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!