Skip to content
Advertisement

How to get next param in linux shell command params?

I’m writing a shell script of this command:

ovs-dump -i dpdkb2 [-d in] [-p tcp] [host 192.168.102.2][port 80] [-w /test.pcap]

For ‘-w’ options, I want to process ‘/test.pcap’ into ‘$PWD/test.pcap’, so I write script like this:

for arg
do
    case $arg in              
        -h | --help)
            ...
            ;;
        -w )
            echo "OPTARG=$OPTARG"
            ;;
        ?)
            ;;
    esac
done

As we see, I want to get ‘/test.pcap’ by ‘$OPTARG’, but is none. So my question is how to get ‘test.pcap’ in my script?

When I use ‘getopts’ like this:

while getopts "w:h:" arg
    do
        case $arg in              
            -h | --help)
                ...
                ;;
            -w )
                echo "OPTARG=$OPTARG"
                ;;
            ?)
                ;;
        esac
    done

When I run sh ovs-dump -w a.pcap, I got error: ‘/usr/local/share/openvswitch/scripts/gangyewei-ovs-dump: line 68: -w: command not found’.

And the output of ‘echo “OPTARG=$OPTARG”‘ is ‘OPTARG=’.

It’s also not work, what should I do? Thank you~

Advertisement

Answer

You can have your script as this:

OPTIND=-1   # rest OPTIND if it has been set earlier

# start getopts loop
while getopts "w:h:" arg; do
    case $arg in
        h | --help)
            ...
        ;;
        w)
            echo "OPTARG=$OPTARG"
        ;;
        ?)

        ;;
    esac;
done

Then run it as:

bash ./ovs-dump -w a.pcap
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement