Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 9th, 2012  |  syntax: None  |  size: 1.12 KB  |  hits: 23  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Converting Bash command line options to variable name
  2. if [ ! -n $1 ]; then
  3.    echo "Error"
  4. fi
  5.        
  6. if test -s "${foo+set}"
  7.        
  8. if [ -z "$1" ]; then
  9.    echo "Error"
  10.    exit 1
  11. fi
  12.        
  13. #!/bin/bash
  14. USAGE="$0: [-a] [--alpha] [-b type] [--beta file] [-g|--gamma] args..."
  15.  
  16. ARGS=`POSIXLY_CORRECT=1 getopt -n "$0" -s bash -o ab:g -l alpha,beta:,gamma -- "$@"`
  17. if [ $? -ne 0 ]
  18.  then
  19.   echo "$USAGE" >&2
  20.   exit 1
  21.  fi
  22. eval set -- "$ARGS"
  23. unset ARGS
  24.  
  25. while true
  26.  do
  27.   case "$1" in
  28.    -a) echo "Option a"; shift;;
  29.    --alpha) echo "Option alpha"; shift;;
  30.    -b) echo "Option b, arg '$2'"; shift 2;;
  31.    --beta) echo "Option beta, arg '$2'"; shift 2;;
  32.    -g|--gamma) echo "Option g or gamma"; shift;;
  33.    --) shift ; break ;;
  34.     *) echo "Internal error!" ; exit 1 ;;
  35.   esac
  36.  done
  37.  
  38. echo Remaining args
  39. for arg in "$@"
  40.  do
  41.   echo '--> '"`$arg'"
  42.  done
  43.  
  44. exit 0
  45.        
  46. if [[ -z $1 ]]; then
  47.     echo "Error"
  48. fi
  49.        
  50. if [ ! -n "$1" ]; then
  51.     echo "Error"
  52. fi
  53.        
  54. -z string
  55.       True if the length of string is zero.
  56.  -n string
  57.       True if the length of string is non-zero.
  58.        
  59. -v varname
  60.       True if the shell variable varname is set (has been assigned a value).