Last active
May 25, 2018 09:57
-
-
Save CristianCantoro/f6ecaa44db75fdfb319f2986292679c9 to your computer and use it in GitHub Desktop.
Example script with docopts
This file contains 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 | |
# shellcheck disable=SC2128 | |
SOURCED=false && [ "$0" = "$BASH_SOURCE" ] || SOURCED=true | |
debug=false | |
parallel=false | |
query='' | |
topic='' | |
read -rd '' docstring <<EOF | |
Usage: | |
esempio.sh [options] --query QUERY --topic TOPIC | |
esempio.sh ( -h | --help ) | |
esempio.sh ( --version ) | |
Options: | |
-d, --debug Enable debug output. | |
-p, --parallel NJOBS Number of parallel jobs [default: 2] | |
-q, --query QUERY Query to perform. | |
-t, --topic TOPIC Topic to process. | |
-h, --help Show this help message and exits. | |
--version Print version and copyright information. | |
---- | |
esempio.sh 0.1.0 | |
copyright (c) 2018 Daniele Foroni | |
MIT License | |
This is free software: you are free to change and redistribute it. | |
There is NO WARRANTY, to the extent permitted by law. | |
EOF | |
eval "$(echo "$docstring" | docopts -V - -h - : "$@" )" | |
# bash strict mode | |
# https://balist.es/blog/2017/03/21/enhancing-the-unofficial-bash-strict-mode/ | |
if ! $SOURCED; then | |
set -euo pipefail | |
IFS=$'\n\t' | |
fi | |
#################### Utils | |
if $debug; then | |
echodebug() { | |
(>&2 echo -en "[$(date '+%F_%k:%M:%S')][DEBUG]\\t") | |
(>&2 echo "$@") | |
} | |
else | |
echodebug() { true; } | |
fi | |
#################### | |
echodebug "debug: $debug" | |
echodebug "parallel: $parallel" | |
echodebug "query: $query" | |
echodebug "topic: $topic" | |
exit 0 |
This file contains 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 | |
# shellcheck disable=SC2128 | |
SOURCED=false && [ "$0" = "$BASH_SOURCE" ] || SOURCED=true | |
if ! $SOURCED; then | |
set -euo pipefail | |
IFS=$'\n\t' | |
fi | |
# controllo il numero di parametri "$#", se meno di 3 -> errore | |
if [ "$#" -le 3 ]; then | |
(>&2 echo "Error: less parameters than expected.") | |
fi | |
primo="$1" | |
secondo="$2" | |
declare -a altri | |
altri=() | |
for i in $(seq 3 $#); do | |
altri+=("${!i}") | |
done | |
echo "primo: $primo" | |
echo "secondo: $secondo" | |
# ${altri[*]} is for printing, if you need to pass to a script | |
# use "${altri[@]}" | |
echo "altri: ${altri[*]}" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment