I want to create script that will have two types of arguments/options.
For example:
./script.sh --date 15.05.05 --host localhost
but I also want to be able to run it with parameters without value:
./script --date 15.0.50.5 --host localhost --logs --config
For now I have something like:
while [[ $# -gt 0 ]]; do
case $1 in
--date|-d ) DATE="$2" ;;
--host|-h ) HOST="$2" ;;
--logs ) LOGS=true ;;
--config ) CONFIG=true ;;
# --all ) LOGS=true ; PROCS=true ; CONFIG=true ;;
* ) usage; exit 1 ;;
esac
shift 2
done
However, when I'm using it like that, I have to put a value after --logs and --config to prevent the shift from taking the next valid parameter, like this:
./script.sh --date 15.05.05 --logs 1 --config 1
Is there any other way?
What about this simple solution?
while [[ $# -gt 0 ]]; do
case $1 in
--date|-d ) DATE="$2" ; shift 2 ;;
--host|-h ) HOST="$2" ; shift 2 ;;
--logs ) LOGS=true ; shift 1 ;;
--config ) CONFIG=true ; shift 1 ;;
* ) usage; exit 1 ;;
esac
done
Or you can use getopts (which only supports short parameters though), approximately like this:
while getopts ":d:h:lc" OPT; do
case $opt in
-d ) DATE="$OPTARG" ;;
-h ) HOST="$OPTARG" ;;
-l ) LOGS=true ;;
-c ) CONFIG=true ;;
* ) usage; exit 1 ;;
esac
done
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