wyatt8740

arg parsing

Oct 6th, 2021
1,051
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.96 KB | None | 0 0
  1. #set some defaults
  2. BUFLEN=80
  3. DOSUDO=0
  4. FFMPEG=0
  5. VOLUME=100
  6. MPLAYER=0
  7. showhelp()
  8. {
  9.   echo 'Supported flags:'
  10.   echo '-b, --buffer-time  : Specify duration of buffer. Default: '"$BUFLEN"'.'
  11.   echo '-f, --use-ffmpeg   : Use ffmpeg instead of an arecord -> aplay pipe.'
  12.   echo '-c, --cap-device   : Use specified device for capturing'
  13.   echo '-m, --use-mplayer  : Use ffmpeg to capture and pipe to mplayer.'
  14.   echo '-r, --root, --nice : Run as root so process can be given higher priority.'
  15.   echo '-v, --volume       : Set volume percentage (implies -f).'
  16.   echo '-h, --help         : Show this help message.'
  17. }
  18. while [ "$#" -gt 0 ]; do
  19.   case "$1" in
  20.     '-b' | '--buffer-time' | '--buffer')
  21.       # shift required whenever an arg-value pair needs passed
  22.       shift 1
  23.       if [ "$#" -gt 0 ]; then
  24.         BUFLEN="$1"
  25.       else
  26.         1>&2 echo 'Error: need a value for buffer duration if -b is passed.'
  27.         exit 1
  28.       fi
  29.       ;;
  30.     '-f' | '--use-ffmpeg')
  31.       FFMPEG=1
  32.       ;;
  33.     '-m' | '--use-mplayer')
  34.       FFMPEG=1
  35.       MPLAYER=1
  36.       ;;
  37.     '-r' | '--root' | '--nice')
  38.       DOSUDO=1
  39.       ;;
  40.     '-v' | '--volume')
  41.       if [ "$#" -gt 1 ]; then
  42.         FFMPEG=1 # -v implies ffmpeg
  43.         VOLUME="$2"
  44.         VOLUME="$(echo '10 k '"$VOLUME"' 100 /p' | dc)"
  45.         shift # param needs a shift-out
  46.       else
  47.         echo 'Error: No volume level to set was given but -v was passed.'
  48.         exit 1
  49.       fi
  50.       ;;
  51.     '-c' | '--cap-device')
  52.       if [ "$#" -gt 1 ]; then
  53.         CAPTURE_DEV="$2"
  54.         shift # param needs a shift-out
  55.       else
  56.         echo 'Error: No volume level to set was given but -v was passed.'
  57.         exit 1
  58.       fi
  59.       ;;
  60.     '-h' | '--help')
  61.       showhelp
  62.       exit 0
  63.       ;;
  64.     *)
  65.       1>&2 echo 'Error: unknown parameters passed to program.'
  66.       1>&2 showhelp
  67.       ;;
  68.   esac
  69.   shift 1
  70.   if [ "$1" = '-b' ]; then
  71.     if [ -z "$2" ]; then
  72.       BUFLEN="$2"
  73.     fi
  74.   fi
  75. done
Advertisement
Add Comment
Please, Sign In to add comment