Pass parameters that contain whitespaces via shell variable

后端 未结 4 1190
南方客
南方客 2021-01-23 12:30

I\'ve got a program that I want to call by passing parameters from a shell variable. Throughout this question, I am going to assume that it is given by

#!/bin/sh         


        
4条回答
  •  时光取名叫无心
    2021-01-23 13:05

    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

提交回复
热议问题