简体   繁体   中英

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM