Search code examples
stringbashgetopts

How to get all input inside quote into variable


I want to insert into variable anything I send inside ".

For example:

check.sh:

#!/bin/bash
./b.sh -a "$@"

b.sh:

#!/bin/bash

while getopts ":a:b:c:" opt; do
  case ${opt} in
        a) A="$OPTARG"
;;
        b) B="$OPTARG"
;;
        c) C="$OPTARG"
;;
        :) echo "bla"
exit 1
;;
esac
done

echo "a: $A, b: $B, c: $C"

Run #1: Desired result:

user@host $  ./check.sh -a asd -b "asd|asd -x y" -c asd
a: -a asd -b "asd|asd -x y" -c asd, b: ,c: 

Actual result:

user@host $  ./check.sh -a asd -b "asd|asd -x y" -c asd
a: -a, b: , c:

Run #2: Desired result:

user@host $ ./check_params.sh -a asd -b asd|asd -c asd
a: -a asd -b asd|asd -c asd, b: ,c:

Actual result:

user@host $ ./check_params.sh -a asd -b asd|asd -c asd
-bash: asd: command not found

Solution

  • Use $* instead of $@:

    check.sh:

    #!/bin/bash
    ./b.sh -a "$*"
    

    "$*" is a string representation of all positional parameters joined together with $IFS variable. Whereas $@ expands into separate arguments.

    Also note that in your 2nd example you need to use quote pipe character string:

    ./check.sh -a asd -b 'asd|asd' -c asd
    

    Check: What is the difference between “$@” and “$*” in Bash?