4

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 ?

1
  • Instead of all those elif statements, use case. Commented Jan 4, 2013 at 7:27

2 Answers 2

5
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.

Sign up to request clarification or add additional context in comments.

Comments

5

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?

1 Comment

don't use getopt but use getopts

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.