Created
July 29, 2020 13:21
-
-
Save retpolanne/7da040872120508b4b4bf3efdbd0cd53 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #/usr/bin/env bash | |
| function _completions() { | |
| COMPREPLY+=("-e") | |
| COMPREPLY+=("--echo") | |
| COMPREPLY+=("--some-flag") | |
| COMPREPLY+=("-c") | |
| COMPREPLY+=("--non-interactive") | |
| COMPREPLY+=("--") | |
| } | |
| complete -F _completions argparse.sh |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| usage="$(basename "$0") [OPTIONS] -- example program | |
| [OPTIONS]: | |
| -h|--help Halp | |
| -e|--echo Text to echo | |
| --some-flag Some flag to set, --some-flag without any parameters and you'll see | |
| -c Something else to echo | |
| --non-interactive Do not prompt for confirmation | |
| -- End of options, pass anything | |
| " | |
| # $# represents the number of arguments | |
| echo "\$\# value is $#" | |
| if [[ $# == 0 ]]; then | |
| echo "$usage" | |
| exit | |
| fi | |
| function proceed() { | |
| echo "Would you like to proceed? Yn" | |
| read choice | |
| case $choice in | |
| [Yy]*) echo "your choice is yes";; | |
| [Nn]*) echo "your choice is no"; exit;; | |
| esac | |
| } | |
| while [[ $# -gt 0 ]]; do | |
| key="$1" | |
| case $key in | |
| -h|--help) | |
| echo "$usage" | |
| exit | |
| ;; | |
| -e|--echo) | |
| TEXT_TO_ECHO=$2 | |
| # use shift to do this weird parameters dance: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_07.html | |
| shift | |
| shift | |
| ;; | |
| -c) | |
| SOMETHING_ELSE_TO_ECHO=$2 | |
| shift | |
| shift | |
| ;; | |
| --some-flag) | |
| FLAG=true | |
| # Use one shift for the flag | |
| shift | |
| ;; | |
| --non-interactive) | |
| NON_INTERACTIVE=true | |
| shift | |
| ;; | |
| --) | |
| echo "End of options" | |
| shift | |
| break | |
| ;; | |
| esac | |
| done | |
| SCRIPT=$@ | |
| echo "Whatever comes after --: $SCRIPT" | |
| if [ -z "$NON_INTERACTIVE" ]; then | |
| proceed | |
| fi | |
| if [ "$SCRIPT" ]; then | |
| echo "Running $SCRIPT" | |
| eval "$SCRIPT" | |
| fi | |
| if [ $FLAG ]; then | |
| echo "Flag set" | |
| fi | |
| if [ -z "$SOMETHING_ELSE_TO_ECHO" ]; then | |
| SOMETHING_ELSE_TO_ECHO=somedefaulttext | |
| fi | |
| echo $TEXT_TO_ECHO | |
| echo $SOMETHING_ELSE_TO_ECHO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment