Sunday, February 26, 2017

Bash Shell and simple way to pass and parse arguments

I was searching of some simple way to take arguments without using third party parser.
Using third party parser with all permutation and combination makes the shell script bigger.

For eg: ./example -a "arg1" -b "-arg2"

I have seen people writing while with case or using getopt. Examples of such are in abandon (so not giving here).

lets get into the code

#!/bin/bash
function usage()
{
  echo "Usage: $0 -a "arg1" -b "arg2"
  exit 0
}

[ $# -eq 0 ] && usage
#add all your options or flags
for ((i=1;i<=$#;i++));
do
  [ ${!i} = "--help" ] || [ ${!i} = "-h" ] && usage
  [ ${!i} = "-a" ] && ((i++)) && A=${!i} && continue
  [ ${!i} = "-b" ] && ((i++)) && B=${!i} && continue
  echo "Wrong argument ${!i} provided. Run with -h"
  usage && exit 0
done

#======Write your program having all the args =====

echo "You have provided $A and $B"

No comments:

Post a Comment