user2930942
user2930942

Reputation: 73

How to get a command line parameter?

suppose I am passing a command line parameters to my shell script as follows :

ex 1 ) ./myshell_script a b c d e f

ex 2 ) ./myshellscript f d e b c a

My question is that , If I want to get the parameter "c" that is always after parameter "b" [ since the command line parameters may be provided in any order ] , How I can get the value that is always after parameter "b" ?

Upvotes: 0

Views: 222

Answers (3)

jkshah
jkshah

Reputation: 11703

myshellscript

#!/bin/bash
grep -oP 'b\s*\K[^ ]+' <<<$*

Test:

% myshellscript a b c d e f
c
% myshellscript f d e b c a
c

Upvotes: 0

Bertrand Caron
Bertrand Caron

Reputation: 2657

Using getopts

It's good practice not to rely on parameters orders, but instead assign them to unambiguous values using getopts. This allow you to write things as ./myshell_script -a a -b b -c c -d d -d e -f f which is equivalent to any permutation of it ./myshellscript -f f -d d -e e -b b -c c -a a.

Not having to worry about order is well worth the couple of extra lines at the beginning of the script and extra characters in its call.

Getopts Tutorial on Bask-hackers

Upvotes: 0

farmer1992
farmer1992

Reputation: 8156

$ ./a.sh f d e b c a
c

code

#!/bin/bash

i=
for p in $@; do

    if [ "$i" == "1" ];then
        echo $p
        exit
    fi
    if [ "$p" == "b" ];then
        i=1
    fi

done

Upvotes: 1

Related Questions