Command line arguments for Bash with getopts


/ Published in: Bash
Save to your folder(s)

How to combine getopts options with (-) and non-options.

After processing all options, variable OPTIND contains the value of the first non-option (commandline argument that doesn't start with (-)).

Shift command will clean previous commandline options.


Copy this code and paste it in your HTML
  1. #!/bin/bash
  2.  
  3. while getopts "u:p:" opt; do
  4.  
  5. case $opt in
  6. u)
  7. echo "-u was triggered, Parameter: $OPTARG"
  8. dbuser="$OPTARG"
  9. ;;
  10. p)
  11. echo "-p was triggered, Parameter: $OPTARG"
  12. dbpass="$OPTARG"
  13. ;;
  14. \?)
  15. echo "Invalid option: -$OPTARG"
  16. exit 1
  17. ;;
  18. :)
  19. echo "Option -$OPTARG requires an argument."
  20. exit 1
  21. ;;
  22. esac
  23.  
  24.  
  25. done
  26.  
  27. # Clear all options and reset the command line
  28. shift $(( OPTIND -1 ))
  29.  
  30. # First parameter
  31. if [ -z "$1" ]; then
  32. echo "usage: $0 [-u name] [-p password] file"
  33. exit
  34. fi

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.