bashcommand-line-argumentsquotation-marks

How do I pass arguments to bash with quotation marks


I have a script which calls a C++ application with command line switches set. What I would like to do is pass the app switches as parameters to the script.

    options=$1
    ...
    ./app $options

The problem occurs when I try to pass an parameter like:

    ./script '-a -C "9.626 0.262 8.266"'

The value of the -C switch is just 9.626 instead of the whole string. Any ideas how to solve this?


Solution

  • You have to use an array.

    options=( -a -C "9.626 0.262 8.266" )
    ./script "${options[@]}"
    

    Inside script, $1 is -a, $2 is -C, and $3 is 9.626 0.262 8.266. (Notice the quotes are not part of $3; they are only used to protect the whitespace while setting the arguments to script. Presumably, you intend to pass all three arguments to some other command, and you would do so with

    other_command "$1" "$2" "$3"
    

    or more generally, to accommodate an arbitrary number of arguments

    other_command "$@"