How do i use options in bash shell scripts?



  • The options to various commands are the -a, -p, -g type syntax you see after a command

    For example -u is an option.

    $ who -u
    

    Shell scripts can also have these options.

    Some info on the commands used in the script:

           shift [n]
                  The positional parameters from n+1 ... are renamed  to  $1  ....
                  Parameters  represented  by  the  numbers  $# down to $#-n+1 are
                  unset.  n must be a non-negative number less than  or  equal  to
                  $#.   If  n is 0, no parameters are changed.  If n is not given,
                  it is assumed to be 1.  If n is greater than $#, the  positional
                  parameters  are  not changed.  The return status is greater than
                  zero if n is greater than $# or less than zero; otherwise 0.
    
           break [n]
                  Exit from within a for, while, until, or select loop.  If  n  is
                  specified, break n levels.  n must be ≥ 1.  If n is greater than
                  the number of enclosing loops, all enclosing loops  are  exited.
                  The  return  value is 0 unless n is not greater than or equal to
                  1.
    
           --        A -- signals the end of options and disables  further  option
                     processing.   Any arguments after the -- are treated as file‐
                     names and arguments.  An argument of - is equivalent to --.
    

    Here's a script that passes three options, -a, -b, and -c, option b has a parameter.

    #!/bin/bash
    while [ -n "$1" ]
    do
      case "$1" in
      -a) echo "The user type option -a";;
      -b) parameter="$2"
      echo "The user typed option -b with a parameter of $parameter"
      shift ;;
      -c) echo "The user types option -c";;
      --) shift
      break ;;
      *) echo "That option $1 does not exist";;
      esac
      shift
    done
    

    The shift command visually.
    0_1535375640161_bash_options.png


Log in to reply
 

© Lightnetics 2024