Last active
November 14, 2018 18:51
-
-
Save harrietty/fa7a44e21b18147634e1d8f378559698 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
#!/bin/bash | |
# A script that outputs each number from start to end | |
# -s 1 to start at one | |
# -e 20 to end at 20 | |
# -b to count backwards | |
# final argument is prefix to all the numbers | |
# e.g. count -s 1 -e 20 -b NUM_ | |
reverse=0 | |
declare -i start=1 | |
declare -i end=10 | |
# You will get an error message if one of the options is missing its arguments, could redirect to /dev/null or use the : at the beginning to put getopts in silent mode | |
while getopts ":s:e:b" opt; do | |
case $opt in | |
b) | |
reverse=1 | |
;; | |
s) | |
[[ "${OPTARG}" =~ ^[0-9]+$ ]] || { echo "Invalid option ${OPTARG} given for -s" >&2; exit 1; } | |
start="${OPTARG}" | |
;; | |
e) | |
[[ "${OPTARG}" =~ ^[0-9]+$ ]] || { echo "Invalid option ${OPTARG} given for -e" >&2; exit 1; } | |
end="${OPTARG}" | |
;; | |
:) | |
# in silent mode, when an option is not given an argument the $opt variable is : and OPTARG is the option name (e.g. e) | |
echo "Option -${OPTARG} is missing an argument" | |
exit 1 | |
;; | |
# In non-silent mode if an option is missing arguments, the $opt variable will be ? | |
# In silent mode, if we have an unknown argument then $opt will be ? | |
\?) | |
echo "Unknown option -${OPTARG}" | |
exit 1 | |
;; | |
esac | |
done | |
echo You have chosen to start at $start and end at $end | |
echo "getopts chomped through all args up to $OPTIND" | |
echo "Shifting arguments" | |
shift $(( $OPTIND - 1 )) | |
echo "Now the first argument is $1" | |
[[ $1 ]] || { echo "No prefix given"; exit 1; } | |
if [[ $reverse -eq 0 ]]; then | |
for (( i=$start; i<$(($end+1)); ++i )); do | |
echo "${1}$i" | |
done | |
else | |
for (( i=$end; i>$(($start-1)); --i )); do | |
echo "${1}$i" | |
done | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment