BASH script and options with / out options

I want to create a script that will have two types of arguments / parameters.

For example:

./script.sh --date 15.05.05 --host localhost

      

but I also want to be able to run it with no value parameters:

./script --date 15.0.50.5 --host localhost --logs --config

      

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 use it this way, I have to put the value after --logs

and --config

to prevent shift

the next valid parameter from being accepted, like this:

./script.sh --date 15.05.05 --logs 1 --config 1

      

Is there another way?

+3


source to share


1 answer


How 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), something 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

      

+3


source







All Articles