Pass parameters that contain whitespaces via shell variable

ぃ、小莉子 提交于 2019-12-02 05:29:10

Use an array to store multiple, space-containing arguments.

$ args=("first one" "second one")
$ count-args "${args[@]}"
2
 count-args "$X"

The quotes ensure in bash, that the whole content of variable X is passed as a single parameter.

This can be solved with xargs. By replacing

count-args $X

with

echo $X | xargs count-args

I can use backslashes to escape whitespaces in $X, e.g.

X="Hello\\ World"
echo $X | xargs count-args

prints out 1 and

X="Hello World"
echo $X | xargs count-args

prints out 2.

chkdsk

Your Counting script:

$ cat ./params.sh
#!/bin/sh
echo $#

For completeness here is what happens with various arguments:

$ ./params.sh
0
$ ./params.sh  1 2
2
$ ./params.sh
0
$ ./params.sh 1
1
$ ./params.sh 1 2
2
$ ./params.sh "1 2"
1

And here is what you get with variables:

$ XYZ="1 2" sh -c './params.sh $XYZ'
2
$ XYZ="1 2" sh -c './params.sh "$XYZ"'
1

Taking this a bit further:

$ cat params-printer.sh
#!/bin/sh
echo "Count: $#"
echo "1 : '$1'"
echo "2 : '$2'"

We get:

$ XYZ="1 2" sh -c './params-printer.sh "$XYZ"'
Count: 1
1 : '1 2'
2 : ''

This looks like what you wanted to do.

Now: If you have a script you cannot control and neither can you control the way the script is invoked. Then there is very little you can do to prevent a variable with spaces turning into multiple arguments.

There are quite a few questions around this on StackOverflow which indicate that you need the ability to control how the command is invoked else there is little you can do.

Passing arguments with spaces between (bash) script

Passing a string with spaces as a function argument in bash

Passing arguments to a command in Bash script with spaces

And wow! this has been asked so many times before:

How to pass argument with spaces to a shell script function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!