Skip to content

Instantly share code, notes, and snippets.

@l0co
Last active September 17, 2020 10:39
Show Gist options
  • Save l0co/0c3187ec07e52707a2e66c97e2e04498 to your computer and use it in GitHub Desktop.
Save l0co/0c3187ec07e52707a2e66c97e2e04498 to your computer and use it in GitHub Desktop.
Bash script with arguments template
#!/bin/bash
CWD=`pwd`
SCRIPT_PATH=`readlink -f "$0"`
SCRIPT_DIR=`dirname "$SCRIPT_PATH"`
cd "$SCRIPT_DIR"
# parse options
QUIET=false
OPT_C=false
OPT_P=
function qecho {
if [[ "$QUIET" == "false" ]]; then
echo "$@"
fi
}
while getopts "qcp:" opt; do
case $opt in
q)
QUIET=true
;;
c)
OPT_C=true
;;
p)
OPT_P="$OPTARG"
;;
\?)
echo "invalid option: -$OPTARG"
cleanExit 1
;;
esac
done
qecho "bash script template"
qecho ""
# exits and cleans up
function cleanExit {
if [[ "$2" != "" ]]; then
echo "$2"
fi
cd $CWD
exit $1
}
# exits with option error message
function handleOptionNotFound {
if [[ "$2" = "" ]]; then
echo "not found option: $1"
cleanExit 1
fi
}
# executed command
function execute {
qecho "exec> $@"
$@
}
function execute_quoted {
qecho "exec> $@"
"$@"
}
# executed command with no output written
function execute_quiet {
qecho "exec> $@"
$@ 2>&1 > /dev/null
}
# load command line arguments
shift $((OPTIND-1))
COMMAND=$1
# execute commands
case "$COMMAND" in
"help")
echo "usage: template [OPTIONS] [COMMAND] [ARGUMENTS]"
echo "-q : quiet mode (no output from this script)"
echo ""
;;
"example-command")
qecho "example-command [param=$2]"
;;
*)
echo "nothing to do, to display help please use: luna help"
cleanExit 1
;;
esac
cleanExit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment