Shell Cheatsheet
Table of contents
Useful Snippets
Project Header
#!/bin/bash
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#
# Tyler(UnclassedPenguin) PROJECT TITLE 2022
#
# Author: Tyler(UnclassedPenguin)
# URL: https://unclassed.ca
# GitHub: https://github.com/UnclassedPenguin
#
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
Good start
Gives you the function “warn” that leads with the name of script.
SCRIPTNAME="${0##*/}"
warn() {
printf >&2 "$SCRIPTNAME: $*\n"
}
usage: warn $"Something to warn about"
To take arguments when running script
ARG1=${1}
ARG2=${2:somedefault}
echo "$ARG1"
Add help usage if arg1 == -h
if [ "$ARG1" == "-h" ] || [ "$ARG1" == "" ]; then
echo "This is the help usage"
exit 0
fi
Second way to take arguments (maybe more proper?)
Help(){
echo "This is help usage"
}
(If multiple options do it like optspec=":huv:"
)
optspec=":h"
while getopts "$optspec" option; do
case $option in
h) # print help usage
Help
exit;;
esac
done
Check For Dependencies
iscmd() {
command -v >&- "$@"
}
checkdeps() {
local -i not_found
for cmd; do
iscmd "$cmd" || {
warn $"$cmd is not found"
let not_found++
}
done
(( not_found == 0 )) || {
warn $"Install dependencies listed above to use $SCRIPTNAME"
exit 1
}
}
# If you need to check more, just add here i.e.:
# checkdeps curl cmd cmd1 cmd2
checkdeps curl
Ask for user confirmation to continue
read -r -p "Continue? [Y/n]" response
response=${response,,} # tolower
if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
dosomethingifyes
else
dosomethingelse
fi
Command or something else if it fails
some command || {
echo "Something went wrong"
exit 1
}
Print success or non success
if some command ; then
echo "command succeed"
else
echo "command failed"
fi