shell command line argument + parsing function

Artis Caune artis.caune at gmail.com
Tue Sep 1 08:19:37 UTC 2009


2009/8/31 Stefan Miklosovic <miklosovic.freebsd at gmail.com>:
> hi,
>
> assuming I execute shell script like this
>
> $ ./script -c "hello world"
>
> I want to save "hello world" string to variable COMMENT in shell script.
>
> code:
>
> #!/bin/sh
>
> parse_cmdline() {
>    while [ $# -gt 0 ]; do
>        case "$1" in
>            -c)
>                shift
>                COMMENT="$1"
>                ;;
>        esac
>        shift
>    done
> }
>
> parse_cmdline $*
>
> echo $COMMENT
>
> exit 0




How about getopts builtin, so you can use:
./script -c "hello world" or
./script -c"hello world" or


while getopts c: f; do
    case $f in
    c)
        COMMENT=$OPTARG
        ;;
    \?)
        echo 'usage: $0 [-c string]'
        exit 1
        ;;
    esac
done

echo "COMMENT: $COMMENT"




-- 
Artis Caune

    Everything should be made as simple as possible, but not simpler.


More information about the freebsd-questions mailing list