I have copied code from tutorialspoint's getopt article and got the following script to work (sort of):
##argument_script.sh
VARS=`getopt -o i::o:: --long input::,output:: -- "$@"`
eval set -- "$VARS"
# extract options and their arguments into variables.
while true ; do
case "$1" in
-i|--input)
case "$2" in
"") MAPPE='/default/input/here/' ; shift 2 ;;
*) MAPPE=$2 ; shift 2 ;;
esac ;;
-o|--output)
case "$2" in
"") OUTPUTFOLDER='/default/input/here/' ; shift 2 ;;
*) OUTPUTFOLDER=$2 ; shift 2 ;;
esac ;;
--) shift ; break ;;
esac
done
echo "${MAPPE}"
echo "${OUTPUTFOLDER}"
#do something here..
that is, I have two optional argument flags -i/--input and -o/-output.
I have a problem with the script currently:
To overwrite the default value of a flag, you need to write the value you want right after the flag, without any spaces.
example: if i wanted to pass /c/ into -i and /f/ into -o, i would need to call the script as: bash argument_script.sh -i/c/ -o/f/. Notice the missing spaces.
If I were to write bash argument_script.sh -i /c/ -o /f/ the variables MAPPE and OUTPUTFOLDER would be using the default values.
Can the script be rewritten, so the arguments passed into -i/-o needs to be written after a space (example: bash argument_script.sh -i /c/ -o /f/)
#!line as the first line of your script?-ito be its value, then there's no other way to pass-iwithout value than by making sure-iis the last argument. Ascmd -i -owould be-iwith-oas the option's argument (like--input=-o)