Bash: pass variable as a single parameter / shell quote parameter

前端 未结 5 1388
孤街浪徒
孤街浪徒 2021-01-23 02:32

I\'m writing a bash script which has to pass a variable to another program:

./program $variable

The problem is, it is absolutely necessary for

相关标签:
5条回答
  • 2021-01-23 03:14

    When you call your script pass the arguments within quotes.

    Example script:

    #!/bin/bash
    for arg in "$@"; do
     echo "arg: $1";
     shift;
    done
    

    When you call it with:

    ./program "parameter with multiple words" parameter2 parameter3 "another parameter"
    

    The output should be:

    arg: parameter with multiple words
    arg: parameter2
    arg: parameter3
    arg: another parameter
    
    0 讨论(0)
  • 2021-01-23 03:16

    The problem seems to be inside the "program"

    variable="Hello World"    # quotes are needed because of the space
    ./program "$variable"     # here quotes again
    

    and inside the program

    echo "program received $# arguments:" 
    i=1
    for arg in "$@"      # again quotes needed
    do echo "arg $((i=i+1)): '$arg'"    # and again
    done
    
    0 讨论(0)
  • 2021-01-23 03:17

    did you try with var="hello world"?

    i tried this in my solaris box.

    > setenv var "hello world"
    > cat temp.sh
    #!/bin/sh
    
    echo $1
    echo $2
    > ./temp.sh "$var"
    hello world
    
    >
    

    as you can see the $2 is not printed.$var is considered as only one argument.

    0 讨论(0)
  • 2021-01-23 03:26

    Have a look on http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html .

    The problem is that the expansion of variables is done before of the command line parameters hence your behavior.

    You might work it arround with setting IFS to something weird as

    IFS='###' V='foo bar baz'; ./program $V 
    
    0 讨论(0)
  • 2021-01-23 03:27

    This is almost certainly a problem in the way you are reading the variable in your program.
    For instance suppose this is your script (just one line for testing):

    echo "$1"
    

    Let's call it echo.sh. If you run echo.sh "test best", you will get test best.

    But if your program says

    echo $1
    

    you might get behaviour like what you're seeing.

    0 讨论(0)
提交回复
热议问题