Home > Enterprise >  Bash while loop with options
Bash while loop with options

Time:12-07

So I have this code and it works fine when running: script and script -n 1.

But when running the script with option: 'script -n` it fails.

I would like to have the help option to pop up then.

Can someone help me?

    while [ -n "${1-}" ]; do
          case $1 in
            -n|--numb_of_times)
              num_of_times="$2"
              shift 2
              ;;
            -h|--help)
              help
              ;;
             *)
              help
              ;;
          esac
        done

CodePudding user response:

Simply modify the -n case:

case $1 in
  -n|--numb_of_times)
    if [ -z "$2" ]; then
      help
    else
      num_of_times="$2"
      shift 2
    fi
    ;;

Or even better:

case $1 in
  -n|--numb_of_times)
    if [ -z "$2" ]; then
      print 'missing number\n'
      help
    else
      num_of_times="$2"
      shift 2
    fi
    ;;
  • Related