Decode command line arguments given to a BASH script


Try the elegant way, at last!

For instance, imagine that your programme has the following arguments:
./myprog -s /source/directory -d /dest/directory -c deep

Then, the script myprog should contain a piece of code like this:

if [ $# -eq 0 ] ; then
echo "Usage: $0 -s -d -c"
exit 1
while [ $# -gt 1 ] ; do
case $1 in
-s) source_dir=$2 ; shift 2 ;;
-d) dest_dir=$2 ; shift 2 ;;
-c) copy_mode=$2 ; shift 2 ;;
*) shift 1 ;;

Of course, this is only a hint. Just tailor the decoding according to your needs.


Tags: ,

7 Responses to “Decode command line arguments given to a BASH script”

  1. Anton Geraschenko Says:

    You can use the bash builtin getopts to do this.

    while getopts "s:d:c:" opt;
    case $opt in
    s) source_dir=$OPTARG ;;
    d) dest_dir=$OPTARG ;;
    c) copy_mode=$OPTARG ;;
    *) echo "Usage: $0 -s -d -c" ; exit 1 ;;

  2. IanVaughanan Says:

    For simple options, I did :

    for option in “$@”; do
    case ${option} in
    -s) OPTION1=1
    -f) OPTION2=1
    *) echo “usage…”

  3. peterhost Says:

    you really made my day. After fighting with getopt and getopts like a madman for hours (and not for the first time) to parse complex command line parameters, the “shift n” method, which I had totally forgotten about took me out of programing-swamp !
    Thx 🙂

  4. abdul rasheed memon Says:

    v nice code dear

  5. Brian Kerhin Says:

    Worked great, but I had to set my while conditional check to 0 for it to process correctly:

    if [ $# -eq 0 ] ; then
    echo “$USAGE”
    exit 1

    while [ $# -gt 0 ] ; do
    case $1 in
    -s) VOLUME=$2 ; shift 2 ;;
    –system) DEST_SERVER=$2 ; shift 2 ;;
    -z) DEST_COMPRESSION=”ON” ; shift 1 ;;
    -r|–rate-limit) RATE_LIMIT=$2 ; shift 2 ;;
    -h|–help) echo $USAGE; exit 1 ; shift 1 ;;
    *) shift 1 ;;

  6. herison Says:

    Use this lib


    optAdd ‘source_dir’ ‘DIR ‘the path to source directory’ ”
    optAddFlag ‘z’ ‘Compress your output’
    optAdd ‘dest_dir’ ‘DIR’ ‘path to the dest dir’ ‘~/output’ # ‘default is home’
    optParse “$@”

    echo $source_dir
    echo $z
    echo $dest_dir

    –help option is generated by lib.
    $ bash -h
    [ –source_dir –z –dest_dir ]

    –source_dir DIR
    the path to source directory

    Compress your output

    –dest_dir DIR
    path to the dest dir

    -h –help
    Display this help and exit.

  7. Takeo Says:

    Whoever edits and pulihsbes these articles really knows what they’re doing.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: