SHARE
TWEET

Untitled

a guest Apr 18th, 2019 82 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. This example shows how to read options and positional arguments from a bash script (same principle can be applied for other shells).
  2.  
  3. ```bash
  4. # some global var we want to overwrite with options
  5. force=false
  6. help=false
  7. log=info
  8. ARGS=() ### this array holds any positional arguments, i.e., arguments not started with dash
  9.  
  10. while [ $# -gt 0 ]; do
  11.     while getopts fhl: name; do
  12.         case $name in
  13.             f) force=true;;
  14.             h) help=true;;
  15.             l) log=$OPTARG;;
  16.         esac
  17.     done
  18.     [ $? -eq 0 ] || exit 1
  19.     [ $OPTIND -gt $# ] && break   # we reach end of parameters
  20.  
  21.     shift $[$OPTIND - 1] # free processed options so far
  22.     OPTIND=1             # we must reset OPTIND
  23.     ARGS[${#ARGS[*]}]=$1 # save first non-option argument (a.k.a. positional argument)
  24.     shift                # remove saved arg
  25. done
  26.  
  27. echo Options: force=$force, help=$help, log=$log
  28. echo Found ${#ARGS[*]} arguments: ${ARGS[*]}
  29. ```
  30.  
  31. Examples:
  32.  
  33. ```bash
  34. $ ./read-args
  35. Options: force=false, help=false, log=info
  36. Found 0 arguments:
  37.  
  38. $ ./read-args -f
  39. Options: force=true, help=false, log=info
  40. Found 0 arguments:
  41.  
  42. $ ./read-args -f -h -l debug
  43. Options: force=true, help=true, log=debug
  44. Found 0 arguments:
  45.  
  46. $ ./read-args -f -h -l debug hello
  47. Options: force=true, help=true, log=debug
  48. Found 1 arguments: hello
  49.  
  50. $ ./read-args hello -f cruel -l debug world
  51. Options: force=false, help=false, log=debug
  52. Found 3 arguments: hello cruel world
  53. ```
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top