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 ?
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With