Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument parsing in bash [duplicate]

Tags:

bash

shell

I am new to bash. Need suggestion for the following problem.

So I want to execute the script in this way

./myscript --bootstrap bootstrap.exe --vmmount ./vmmount --image /dev/sdb2 --target-exe installer.exe [--internal-exe] param1 param2 param3 ...

Argument parser i have done:

VMMOUNT=""
BOOTSTRAP=""
IMAGE_FILE=""
TARGET_EXE=""
INTERNAL_EXE=""
while : ; do
if [ "$1" = "--vmmount" ] ; then
    [ -n "${VMMOUNT}" ] && usage
    VMMOUNT="$2"
    shift
    shift
elif [ "$1" = "--bootstrap" ] ; then
    [ -n "${BOOTSTRAP}" ] && usage
    BOOTSTRAP="$2"
    shift
    shift
elif [ "$1" = "--image" ] ; then
    [ -n "${IMAGE_FILE}" ] && usage
    IMAGE_FILE="$2"
    shift
    shift       
elif [ "$1" = "--target-exe" ] ; then
    [ -n "${TARGET_EXE}" ] && usage
    TARGET_EXE="$2"
    shift
    shift
elif [ "$1" = "--internal-exe" ] ; then
    [ -n "${INTERNAL_EXE}" ] && usage
    INTERNAL_EXE="true"
    shift
    shift
else
    break
fi
done
my_method "${IMAGE_FILE}" "${VMMOUNT}" "${BOOTSTRAP}" "${TARGET_EXE}" "${INTERNAL_EXE}" 

Now I have confusion in parsing the parameters param1 and param2 etc. How to parse them ? Can I use $@ to take the params as array or any other efficient way ?

like image 521
Reuben Avatar asked Dec 26 '22 12:12

Reuben


2 Answers

VMMOUNT=""
BOOTSTRAP=""
IMAGE_FILE=""
TARGET_EXE=""
INTERNAL_EXE=""
while : ; do
  case "$1" in 
    --vmmount)
       [ -n "${VMMOUNT}" ] && usage
       VMMOUNT="$2"
       shift 2 ;;
    --bootstrap)
       [ -n "${BOOTSTRAP}" ] && usage
       BOOTSTRAP="$2"
       shift 2 ;;
    --image)
       [ -n "${IMAGE_FILE}" ] && usage
       IMAGE_FILE="$2"
       shift 2 ;;    
    --target-exe)
       [ -n "${TARGET_EXE}" ] && usage
       TARGET_EXE="$2"
       shift 2 ;;
    --internal-exe)
       [ -n "${INTERNAL_EXE}" ] && usage
       INTERNAL_EXE="true"
       shift ;;
    *)
       break ;;
  esac
done
my_method "${IMAGE_FILE}" "${VMMOUNT}" "${BOOTSTRAP}" "${TARGET_EXE}" "${INTERNAL_EXE}" "$@"

Don't forget to enclose $@ in double quotes.

like image 131
Barmar Avatar answered Dec 29 '22 01:12

Barmar


I would suggest you use getopt to parse your command line arguements instead of hand coding it. It should save a lot of time.

Also shown in How do I parse command line arguments in Bash?

like image 36
Karthik T Avatar answered Dec 29 '22 02:12

Karthik T