use bash
#!/bin/bash
# -e - exit when a command fails (b/c e.g. it doesn't exist). Use ` || true` to override this.
# -u - catch unset variables
# -o pipefail - piping bad commands into other commands will now fail
# -E - trap
set -Eeuo pipefail
If
if [[ <some test> ]]
then
<commands>
else
<other commands>
fi
Case
case $my_var in
ecom) echo "$ZV_ECOM";;
cg) echo "$ZV_CG" ;;
jp) echo "$ZV_JP" ;;
*) return 1
esac
# single-character flags only
# flags that take an arg have a `:` after then
# Begin the opts string with a colon (e.g. ':habs') in order to suppress error message
#
# If using this in a function, you need to add `OPTIND=1` before this
while getopts "habs:" opt; do
case $opt in
h)
$COMOTO_CLI_LIB/render_help
return 0
;;
a)
do_ansible=1
;;
b)
do_remove_redline_build=1
;;
s)
what_to_bounce=$OPTARG
;;
*) echo "$0: error" >&2; return 1
esac
done
- If sourcing a script (i.e. not an executable),
you'll have to set
OPTIND=1
.
while :; do
case "${1-}" in
-h|--help) $COMOTO_CLI_LIB/render_help; return 0;;
--opt-with-val) my_val=$2; shift;;
-t) text_only='true' ;;
*) break ;;
esac
shift
done
If the args are all flags (i.e. they don't take params), do this:
for arg in "$@"
do
case $arg in
-h|--help) $COMOTO_CLI_LIB/render_help; return 0;;
-c) confirmation_option='-c';;
-d) _add_db_migrate_task 'down';;
-l) _add_db_migrate_task 'lock';;
-u) _add_db_migrate_task 'up';;
*)
>&2 echo invalid input! "($1)"
_comoto_cli_help
return 1
;;
esac
done
chmod u+x <filename>
if [[ $# -eq 0 ]]; then
# do something if no args
fi
Confirmation
while true; do
read -p "Do you want to proceed? [Y/n] " yn
case $yn in
[Yy]* ) return 0;;
[Nn]* ) return 1;;
* ) echo "Please answer yes or no.";;
esac
done
https://opensource.com/article/18/5/you-dont-know-bash-intro-bash-arrays
# initialize
myArray=(string1 string2 three 4)
emptyArray=()
# Index access
# - zero-indexed
# - curly braces required
echo ${myArray[1]}
# print all elements
echo ${myArray[@]}
# loop over elements
for e in ${myArray[@]}
do
echo $e
done
# Add elements
myArray+=(five 6)
compgen -c