简体   繁体   中英

shell script pass argument with space

I have the following script (example):

#!/bin/bash
while getopts a: opt; do
    case "$opt" in
        a) val="$OPTARG";;
        ?) echo "use the flag \"-a\""
           exit 2;;
    esac
done
echo "a specified with: ${val}"  

When I now call this script with test.sh -a "here is a string" the output is: a specified with: here but not as I would like to have a specified with: here is a string .

I know that I can call the script with test.sh -a here\\ is\\ a\\ string or test.sh -a "here\\ is\\ a\\ string" and it will work. But in my case I can not manipulate the string I want to pass.
So how can I change my getopts function to make it work?

I also tried getopt , but I worked even more wors:

commandsShort="a:"
commandsLong="aval:"
TEMP=`getopt \
        -o $commandsShort \
        -l $commandsLong \
        -q \
        -n "$0" -- "$@"`

What am I doing wrong?

This got solved in comments on your question. :-)

You're calling the script with:

eval "test.sh $@"

The effect of this "eval" line, if "here is a string" is your option, is to create the command line that is in the quotes:

test.sh here is a string

and eval uate it.

Per the additional comments, if you can avoid eval, you should.

That said, if you need it, you could always quote the string within the eval:

eval "test.sh \"$@\""

Or if you don't like escaping quotes, use singles, since your $@ will be expanded due to the outer quotes being double:

eval "test.sh '$@'"

And finally, as you mentioned in comments, just running directly may be the best option:

test.sh "$@"

Note that if your $@ includes the -a option, you may have a new problem. Consider the command line:

test.sh "-a here is a string"

In this case, your entire string, starting with -a , is found in $1 , and you will have no options for getopts and no OPTARG.

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