문제

I have a bash script, which I want to call like this:

bash curl.sh http://www.google.co.uk/ -d Directory -a "Moz 123" -r http://localhost/

I can collect the first argument (http://www.google.co.uk/), with the following:

url=$1
while getopts p:d:a:r: opt; do
case $opt in
    p) proxy=$OPTARG ;;
    d) dir=$OPTARG ;;
    a) ua=$OPTARG ;;
    r) ref=$OPTARG ;;
esac
done

However, it does not pick up the other -arguments. If I remove 'http://www.google.co.uk/' as the first argument, it picks up the -arguments.

Due to logistics, I am not able to set the first argument, e.g. 'http://www.google.co.uk/' with -u etc.

How do you get this to work?

도움이 되었습니까?

해결책 3

In my case, this seems the best option:

Call the script like:

bash curl.sh -d Remote -a "Moz 123" -r http://localhost http://www.google.com/

You can pick the last argument up like:

url=${!#}

And then the other options using getopts, as above.

다른 팁

Why not pass arguments in, wrapped in quotes?

e.g.

script.shl "http://www.google.com" "/var/www/test" "option 3"

...then you can just access them directly in the script using $1 $2 $3. You can still alter the course of the script by just using if...else?

Unless, I've mis-read your question...

getopts stops parsing as soon as it sees an argument that does not begin with a hyphen. You'll have to change the order in which you pass the arguments, or use the GNU version of the external getopt program, which can handle regular arguments mixed in with options.

I think the following should work (it's modeled on your code and an example at http://linuxaria.com/howto/parse-options-in-your-bash-script-with-getopt?lang=en). Essentially, getopt just reorders the arguments and breaks apart any combine options (like changing -xyz to -x -y -z). Any non-optional arguments will be found after -- in the parsed option list.

PARSED_OPTIONS=$( getopt -o "p:d:a:r:" -- "$@" )
eval set -- "$PARSED_OPTIONS"
while true; do
    case $1 in
        p) proxy=$2; shift 2 ;;
        d) dir=$2; shift 2 ;;
        a) ua=$2; shift 2 ;;
        r) ref=$2; shift 2;;
        --) shift; break ;;
    esac
done
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top