简体   繁体   中英

Manipulate variables containing quoted strings in a BASH script

I have to pass a variable like data='Type=Eatable Fruits="Apple Orange"' to a bash script (print.sh) that simply print the first, second, than third command line argument, one by line.

When I passed the variable data to the script, by running: sh print.sh $data , the output was

Type=Eatable
Fruits="Apple
Orange"

But then need was

Type=Eatable
Fruits="Apple Orange"
 

The second line should also print double-quotes. ( Third argument should be NULL/Nothing )

What should I change to get output like above?

When you run sh print.sh $data , it gets tokenized like this:

[ sh , print.sh , $data ]

Because $data is not quoted, the value of the variable data gets tokenized to

[ Fruits="Apple , Orange" ]

Which is then added to the original command to make

[ sh , print.sh , Fruits="Apple , Orange" ]

And print.sh gets called with $1= Fruits="Apple , $2= Orange"

It sounds like you actually wanted this to be one parameter to print.sh , not two. Using "$data" instead of $data will make this happen, as per Pierre-Louis Laffont's answer

Make your call with you variable between double quotes :

$ ./script.sh $data
Fruits="Apple
Orange"

$ ./script.sh "$data"  
Fruits="Apple Orange"

My two cents, script will need modification. Are you using

echo $1
echo $2

you should try

echo $1 $2

When you passed the string I suspect that everything was taken as arg1 and arg2 was empty. Confirm by printing $#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM