bash shebang ↑
#!/usr/bin/env ${1|bash,node,perl,php,python,python3,ruby|}Script summary ↑
# Title: title
# Description: description
# Author: author <email>
# Date: yyyy-mm-dd
# Version: 1.0.0function ↑
function name () {
echo "$1" # arguments are accessible through $1, $2,...
}number of function arguments ↑
echo $#function arguments array ↑
echo "$@"last function/command return code ↑
echo "$?"run command (command substitution) ↑
`command`check if last command succeed ↑
if [[ $? == 0 ]]; then
echo command succeed
ficheck if last command failed ↑
if [[ $? != 0 ]]; then
echo command failed
fiassign elements to an array ↑
newArray=("Element 1" "Element 2")assign default to variable if variable is empty or null ↑
: "${variable:=default}"Ask question with default answer ↑
read -ep "Question here? " -i Default answer ANSWER
echo "$ANSWER"create directory ↑
mkdir dirnamecreate nested directories ↑
mkdir -p parent dir/child dirif ↑
if [ condition ]; then
# body
elif [ condition ]; then
# body
else
# body
fiif condition is true then run command (short circuit) ↑
[ condition ] && commandif condition is false then run command (short circuit) ↑
[ condition ] || commandif string is empty ↑
if [ -z "$string" ]; then
# body
fiif string is not empty ↑
if [ -n "$string" ]; then
# body
fiif strings are equal ↑
if [ "$string1" = "$string2" ]; then
# body
fiif strings are not equal ↑
if [ "$string1" != "$string2" ]; then
# body
filength of string in characters ↑
length=${#variable}remove leading and trailing white space(s) ↑
trimmed=`echo -e "${var}" | sed -e 's/^[[:space:]]*//' | sed -e 's/[[:space:]]*$//'`remove leading white space(s) ↑
trimmed=`echo -e "${var}" | sed -e 's/^[[:space:]]*//'`remove trailing white space(s) ↑
trimmed=`echo -e "${var}" | sed -e 's/[[:space:]]*$//'`remove all white space(s) ↑
trimmed=`echo -e "${var}" | tr -d '[[:space:]]'`find all occurrences of a substrings and replace them ↑
replaced=`echo -e "${var}" | sed -e 's/find/replace/g'`reverse string characters ↑
reversed=`echo -e "${var}" | rev`convert string to lowercase ↑
toLower=`echo -e "${var}" | tr '[:upper:]' '[:lower:]'`convert string to uppercase ↑
toUpper=`echo -e "${var}" | tr '[:lower:]' '[:upper:]'`part of the string from offset with length characters ↑
substring=`echo -e "${var:offset:length}"`check whether string contains substring ↑
if [[ "$string" = *substring* ]]; then
# body
fifirst index of substring in string ↑
temp=${string%%"substring"*} && indexOf=`echo ${string%%"substring"*} | echo ${#temp}`
# echo $indexOfif integers are equal ↑
if [[ $int1 == $int2 ]]; then
echo equal
fiif integers are not equal ↑
if [[ $int1 != $int2 ]]; then
echo not equal
fiif integer greater than value ↑
if [[ $int > $${2:val} ]]; then
echo greater
fiif integer greater than or equal value ↑
if [[ $int >= $val ]]; then
echo greater equal
fiif integer lesser than value ↑
if [[ $int > $${2:val} ]]; then
echo lesser
fiif integer lesser than or equal value ↑
if [[ $int <= $val ]]; then
echo lesser equal
ficheck if command exists ↑
if [ `command -v command` ]; then
# body
fiif path exists (file, directory, link...) ↑
if [ -e "$path"; then
echo exists
fiif file exists ↑
if [ -f "$file" ]; then
echo file exists
fiif file size is greater than zero ↑
if [ -s "$file" ]; then
echo file not empty
fiif directory exists ↑
if [ -d "$directory" ]; then
echo directory exists
fiif file readable ↑
if [ -r "$file" ]; then
echo file is readable
fiif file writeable ↑
if [ -w "$file" ]; then
echo file is writeable
fiif file executable ↑
if [ -x "$file" ]; then
echo file is executable
fiif files are equal ↑
if [ "$file1" -ef "$file2" ]; then
echo files are equal
fiif file exists and is a symbolic link ↑
if [ -h "$file" ]; then
echo symbolic link
fiif file1 newer than file2 ↑
if [ "$file1" -nt "$file2" ]; then
echo file1 is newer than file2
fiif file1 older than file2 ↑
if [ "$file1" -ot "$file2" ]; then
echo file1 is older than file2
fiArray of local IPs ↑
IPS=`hostname -I`public ip information ↑
echo `curl -s ipinfo.io/${1|ip,city,region,country,loc,postal,org|}`public ip address ↑
PUBLIC_IP=`curl -s ${1|bot.whatismyipaddress.com,ident.me,ipecho.net/plain,icanhazip.com,ifconfig.me,api.ipify.org,ipinfo.io/ip|}`for loop by index ↑
for((i=0;i<n;i++)); do
echo "$i"
donefor loop by index ↑
for((i=0;i<n;i++)); do
for((j=0;j<m;j++)); do
echo "$i, $j"
done
donefor loop in collection ↑
for item in {a..z}; do
echo "$item"
donefor loop in collection ↑
for col in `docker images | awk '{ print $1":"$2 }'`; do
echo "$col" | cut -d ':' -f 1
echo "$col" | cut -d ':' -f 2
donewhile loop ↑
while [ condition ]; do
# body
doneuntil loop ↑
until [ condition ]; do
# body
doneswitch case ↑
case "$item" in
1)
echo "case 1"
;;
2|3)
echo "case 2 or 3"
;;
*)
echo "default"
;;
esacarithmetic operations ↑
expr 2 * 3increment variable ↑
$((${1|var++,++var|}))decrement variable ↑
$((${1|var--,--var|}))add two variables (+= assign result to var1) ↑
$((var1 ${2|+,+=|} var2))subtract var2 from var1 (-= assign result to var1) ↑
$((var1 ${2|-,-=|} var2))multiply var1 and var2 (*= assign result to var1) ↑
$((var1 ${2|*,*=|} var2))divide var1 by var2 (/= assign result to var1) ↑
$((var1 ${2|/,/=|} var2))reminder of dividing var1 by var2 (%= assign result to var1) ↑
$((var1 ${2|%,%=|} var2))exponentiate base to power ↑
$((base ** power))square root of var up to scale decimal places ↑
result=`echo "scale=${2|0,1,2,3,4,5,6,7,8,9|};sqrt($var)" | bc`math operations with up to scale decimal places precision ↑
result=`echo "scale=${2|0,1,2,3,4,5,6,7,8,9|};($var1 ${4|+,-,*,/,^|} $var2)" | bc`math PI constant ↑
MATH_PI='3.14159265358979323846264338327950288'math Napier's constant ↑
MATH_NAPIER='2.71828182845904523536028747135266249'math Euler-Mascheroni constant ↑
MATH_GAMMA='0.57721566490153286060651209008240243'math golden ration constant ↑
MATH_GOLDEN_RATIO='1.61803398874989484820458683436563811'math Omega constant ↑
MATH_OMEGA='0.56714329040978387299996866221035554'read a file ↑
cat "$filepath" | while read line; do
echo "$line"
donewrite a file ↑
echo "file header" > ${2:"$filepath"}
for line in {lines}; do
echo "$line" >> "$filepath"
donewrite multiple lines into file ↑
cat >filepath <<EOL
# text here
EOLwrite multiple lines into file with sudo permission ↑
cat << EOL | sudo tee filepath
# text here
EOLfind and remove files older than x days ↑
find "$path" -mtime +days | xargs rm -fwrite in black ↑
echo `tput setaf 0`black text`tput sgr0`write in red ↑
echo `tput setaf 1`red text`tput sgr0`write in green ↑
echo `tput setaf 2`green text`tput sgr0`write in yellow ↑
echo `tput setaf 3`yellow text`tput sgr0`write in blue ↑
echo `tput setaf 4`blue text`tput sgr0`write in magenta ↑
echo `tput setaf 5`magenta text`tput sgr0`write in cyan ↑
echo `tput setaf 6`cyan text`tput sgr0`write in white ↑
echo `tput setaf 7`white text`tput sgr0`write in bold ↑
echo `tput bold`bold text`tput sgr0`write in italic ↑
echo `tput sitm`italic text`tput sgr0`write in dim ↑
echo `tput dim`dimmed text`tput sgr0`write in reverse ↑
echo `tput rev`reversed text`tput sgr0`generate random integer x such as min < x < max ↑
echo $((min + RANDOM % $((max-min))))Comment out a special region (i.e. variable declarations ↑
# >>>>>>>>>>>>>>>>>>>>>>>> name >>>>>>>>>>>>>>>>>>>>>>>>
$0
# <<<<<<<<<<<<<<<<<<<<<<<< name <<<<<<<<<<<<<<<<<<<<<<<<Manage service operations ↑
sudo systemctl ${1|enable,disable,start,stop,reload,restart,status|} servicestart stopwatch ↑
STOPWATCH_START_TIME=$(date +%s)stop stopwatch ↑
STOPWATCH_END_TIME=$(date +%s)elapsed time ↑
STOPWATCH_ELAPSED_TOTAL_SECONDS=$((STOPWATCH_END_TIME - STOPWATCH_START_TIME))
STOPWATCH_ELAPSED_MINUTES=$((STOPWATCH_ELAPSED_TOTAL_SECONDS / 60))
STOPWATCH_ELAPSED_SECONDS=$((STOPWATCH_ELAPSED_TOTAL_SECONDS % 60))
echo elapsed $STOPWATCH_ELAPSED_MINUTES minutes and $STOPWATCH_ELAPSED_SECONDS secondssleep for a specified amount of time (s: second, m: minute, h: hour, d: day) ↑
sleep 30${2|s,m,h,d|}Run command within a time frame ↑
timeout seconds commandfunction: print a banner with provided title ↑
# Usage: banner_simple "my title"
function banner_simple() {
local msg="* $* *"
local edge=`echo "$msg" | sed 's/./*/g'`
echo "$edge"
echo "`tput bold`$msg`tput sgr0`"
echo "$edge"
echo
}call banner_simple function ↑
banner_simple "my title"print a color banner. ↑
# Usage: banner_color green "my title"
function banner_color() {
local color=$1
shift
case $color in
black) color=0
;;
red) color=1
;;
green) color=2
;;
yellow) color=3
;;
blue) color=4
;;
magenta) color=5
;;
cyan) color=6
;;
white) color=7
;;
*) echo "color is not set"; exit 1
;;
esac
local s=("$@") b w
for l in "${s[@]}"; do
((w<${#l})) && { b="$l"; w="${#l}"; }
done
tput setaf $color
echo " =${b//?/=}=
| ${b//?/ } |"
for l in "${s[@]}"; do
printf '| %s%*s%s |\n' "$(tput setaf $color)" "-$w" "$l" "$(tput setaf $color)"
done
echo "| ${b//?/ } |
=${b//?/=}="
tput sgr 0
}call banner_color function ↑
banner_color ${1|black,red,green,yellow,blue,magenta,cyan,white|} "my title"import functions from other shellscript files ↑
# Usage: import "mylib"
function import() {
local file="./lib/$1.sh"
if [ -f "$file" ]; then
source "$file"
else
echo "Error: Cannot find library at: $file"
exit 1
fi
}call import function, to import functions from other shellscript files located in a directory (default: lib) relative to current script file ↑
import "libname"provide a list of options to user and return the index of selected option ↑
# Usage: options=("one" "two" "three"); chooseOption "Choose:" 1 "${options[@]}"; choice=$?; echo "${options[$choice]}"
function chooseOption() {
echo "$1"; shift
echo `tput sitm``tput dim`-"Change selection: [up/down] Select: [ENTER]" `tput sgr0`
local selected="$1"; shift
ESC=`echo -e "\033"`
cursor_blink_on() { tput cnorm; }
cursor_blink_off() { tput civis; }
cursor_to() { tput cup $(($1-1)); }
print_option() { echo `tput dim` " $1" `tput sgr0`; }
print_selected() { echo `tput bold` "=> $1" `tput sgr0`; }
get_cursor_row() { IFS=';' read -sdR -p $'\E[6n' ROW COL; echo ${ROW#*[}; }
key_input() { read -s -n3 key 2>/dev/null >&2; [[ $key = $ESC[A ]] && echo up; [[ $key = $ESC[B ]] && echo down; [[ $key = "" ]] && echo enter; }
for opt; do echo; done
local lastrow=`get_cursor_row`
local startrow=$(($lastrow - $#))
trap "cursor_blink_on; echo; echo; exit" 2
cursor_blink_off
: selected:=0
while true; do
local idx=0
for opt; do
cursor_to $(($startrow + $idx))
if [ $idx -eq $selected ]; then
print_selected "$opt"
else
print_option "$opt"
fi
((idx++))
done
case `key_input` in
enter) break;;
up) ((selected--)); [ $selected -lt 0 ] && selected=$(($# - 1));;
down) ((selected++)); [ $selected -ge $# ] && selected=0;;
esac
done
cursor_to $lastrow
cursor_blink_on
echo
return $selected
}call options function ↑
options=("one" "two" "three")
chooseOption "Choose:" 1 "${options[@]}"; choice=$?
echo "${options[$choice]}" selectedScan host's port range (tcp/udp) ↑
# Usage: scan proto host fromPort toPort
function scan () {
for ((port=$3; port<=$4; port++)); do
(echo >/dev/$1/$2/$port) >/dev/null 2>&1 && echo "$1 $port => open"
done
}call scan function to scan a host over a port range ↑
scan ${1|tcp,udp|} host fromPort toPort