Skip to content

Latest commit

 

History

History
1326 lines (877 loc) · 20.5 KB

File metadata and controls

1326 lines (877 loc) · 20.5 KB

Commands

bash

bash shebang

#!/usr/bin/env ${1|bash,node,perl,php,python,python3,ruby|}

summary

Script summary

# Title:         title
# Description:   description
# Author:        author <email>
# Date:          yyyy-mm-dd
# Version:       1.0.0

func

function

function name () {
  echo "$1" # arguments are accessible through $1, $2,...
}

func args count

number of function arguments

echo $#

func args

function arguments array

echo "$@"

func ret val

last function/command return code

echo "$?"

cmd

run command (command substitution)

`command`

cmd success check

check if last command succeed

if [[ $? == 0 ]]; then
  echo command succeed
fi

cmd failure check

check if last command failed

if [[ $? != 0 ]]; then
  echo command failed
fi

assign array

assign elements to an array

newArray=("Element 1" "Element 2")

assign if empty

assign default to variable if variable is empty or null

: "${variable:=default}"

ask question

Ask question with default answer

read -ep "Question here? " -i Default answer ANSWER
echo "$ANSWER"

directory create

create directory

mkdir dirname

directory create nested

create nested directories

mkdir -p parent dir/child dir

if

if

if [ condition ]; then
   # body
elif [ condition ]; then
   # body
else
   # body
fi

iff

if condition is true then run command (short circuit)

[ condition ] && command

iff not

if condition is false then run command (short circuit)

[ condition ] || command

if string empty

if string is empty

if [ -z "$string" ]; then
  # body
fi

if string not empty

if string is not empty

if [ -n "$string" ]; then
  # body
fi

if string =,string equal

if strings are equal

if [ "$string1" = "$string2" ]; then
  # body
fi

if string !=,string not equal

if strings are not equal

if [ "$string1" != "$string2" ]; then
  # body
fi

string length

length of string in characters

length=${#variable}

string trim

remove leading and trailing white space(s)

trimmed=`echo -e "${var}" |  sed -e 's/^[[:space:]]*//' | sed -e 's/[[:space:]]*$//'`

string trim left

remove leading white space(s)

trimmed=`echo -e "${var}" | sed -e 's/^[[:space:]]*//'`

string trim right

remove trailing white space(s)

trimmed=`echo -e "${var}" | sed -e 's/[[:space:]]*$//'`

string trim all

remove all white space(s)

trimmed=`echo -e "${var}" | tr -d '[[:space:]]'`

string replace

find all occurrences of a substrings and replace them

replaced=`echo -e "${var}" | sed -e 's/find/replace/g'`

string reverse

reverse string characters

reversed=`echo -e "${var}" | rev`

string toLower

convert string to lowercase

toLower=`echo -e "${var}" | tr '[:upper:]' '[:lower:]'`

string toUpper

convert string to uppercase

toUpper=`echo -e "${var}" | tr '[:lower:]' '[:upper:]'`

string substring

part of the string from offset with length characters

substring=`echo -e "${var:offset:length}"`

string contains,if string contains

check whether string contains substring

if [[ "$string" = *substring* ]]; then
  # body
fi

string indexOf

first index of substring in string

temp=${string%%"substring"*} && indexOf=`echo ${string%%"substring"*} | echo ${#temp}`
# echo $indexOf

if int =

if integers are equal

if [[ $int1 == $int2 ]]; then
  echo equal
fi

if int !=

if integers are not equal

if [[ $int1 != $int2 ]]; then
  echo not equal
fi

if int >

if integer greater than value

if [[ $int > $${2:val} ]]; then
  echo greater
fi

if int >=

if integer greater than or equal value

if [[ $int >= $val ]]; then
  echo greater equal
fi

if int <

if integer lesser than value

if [[ $int > $${2:val} ]]; then
  echo lesser
fi

if int <=

if integer lesser than or equal value

if [[ $int <= $val ]]; then
  echo lesser equal
fi

if cmd exists

check if command exists

if [ `command -v command` ]; then
  # body
fi

if exists

if path exists (file, directory, link...)

if [ -e "$path"; then
  echo exists
fi

if file exists

if file exists

if [ -f "$file" ]; then
  echo file exists
fi

if file not empty

if file size is greater than zero

if [ -s "$file" ]; then
  echo file not empty
fi

if directory exists

if directory exists

if [ -d "$directory" ]; then
  echo directory exists
fi

if file readable

if file readable

if [ -r "$file" ]; then
  echo file is readable
fi

if file writeable

if file writeable

if [ -w "$file" ]; then
  echo file is writeable
fi

if file executable

if file executable

if [ -x "$file" ]; then
  echo file is executable
fi

if file =

if files are equal

if [ "$file1" -ef "$file2" ]; then
  echo files are equal
fi

if file link

if file exists and is a symbolic link

if [ -h "$file" ]; then
  echo symbolic link
fi

if file newer

if file1 newer than file2

if [ "$file1" -nt "$file2" ]; then
  echo file1 is newer than file2
fi

if file older

if file1 older than file2

if [ "$file1" -ot "$file2" ]; then
  echo file1 is older than file2
fi

ips

Array of local IPs

IPS=`hostname -I`

ip info

public ip information

echo `curl -s ipinfo.io/${1|ip,city,region,country,loc,postal,org|}`

ip public

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 i

for loop by index

for((i=0;i<n;i++)); do
  echo "$i"
done

for ij

for loop by index

for((i=0;i<n;i++)); do
  for((j=0;j<m;j++)); do
    echo "$i, $j"
  done
done

for in

for loop in collection

for item in {a..z}; do
  echo "$item"
done

for in column

for 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
done

while

while loop

while [ condition ]; do
  # body
done

until

until loop

until [ condition ]; do
  # body
done

switch case

switch case

case "$item" in
  1)
    echo "case 1"
  ;;
  2|3)
    echo "case 2 or 3"
  ;;
  *)
    echo "default"
  ;;
esac

expr

arithmetic operations

expr 2 * 3

math ++

increment variable

$((${1|var++,++var|}))

math --

decrement variable

$((${1|var--,--var|}))

math +

add two variables (+= assign result to var1)

$((var1 ${2|+,+=|} var2))

math -

subtract var2 from var1 (-= assign result to var1)

$((var1 ${2|-,-=|} var2))

math *

multiply var1 and var2 (*= assign result to var1)

$((var1 ${2|*,*=|} var2))

math /

divide var1 by var2 (/= assign result to var1)

$((var1 ${2|/,/=|} var2))

math %

reminder of dividing var1 by var2 (%= assign result to var1)

$((var1 ${2|%,%=|} var2))

math ^

exponentiate base to power

$((base ** power))

math √

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 0.00

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 const π

math PI constant

MATH_PI='3.14159265358979323846264338327950288'

math const e

math Napier's constant

MATH_NAPIER='2.71828182845904523536028747135266249'

math const 𝛾

math Euler-Mascheroni constant

MATH_GAMMA='0.57721566490153286060651209008240243'

math const ϕ

math golden ration constant

MATH_GOLDEN_RATIO='1.61803398874989484820458683436563811'

math const Ω

math Omega constant

MATH_OMEGA='0.56714329040978387299996866221035554'

file read

read a file

cat "$filepath" | while read line; do
  echo "$line"
done

file write

write a file

echo "file header" > ${2:"$filepath"}
for line in {lines}; do
  echo "$line" >> "$filepath"
done

file write multiline

write multiple lines into file

cat >filepath <<EOL
# text here
EOL

file write multiline sudo

write multiple lines into file with sudo permission

cat << EOL | sudo tee filepath
# text here
EOL

remove files older

find and remove files older than x days

find "$path" -mtime +days | xargs rm -f

color black

write in black

echo `tput setaf 0`black text`tput sgr0`

color red

write in red

echo `tput setaf 1`red text`tput sgr0`

color green

write in green

echo `tput setaf 2`green text`tput sgr0`

color yellow

write in yellow

echo `tput setaf 3`yellow text`tput sgr0`

color blue

write in blue

echo `tput setaf 4`blue text`tput sgr0`

color magenta

write in magenta

echo `tput setaf 5`magenta text`tput sgr0`

color cyan

write in cyan

echo `tput setaf 6`cyan text`tput sgr0`

color white

write in white

echo `tput setaf 7`white text`tput sgr0`

format bold

write in bold

echo `tput bold`bold text`tput sgr0`

format italic

write in italic

echo `tput sitm`italic text`tput sgr0`

format dim

write in dim

echo `tput dim`dimmed text`tput sgr0`

format reverse

write in reverse

echo `tput rev`reversed text`tput sgr0`

random int

generate random integer x such as min < x < max

echo $((min + RANDOM % $((max-min))))

region

Comment out a special region (i.e. variable declarations

# >>>>>>>>>>>>>>>>>>>>>>>> name >>>>>>>>>>>>>>>>>>>>>>>>
$0
# <<<<<<<<<<<<<<<<<<<<<<<< name <<<<<<<<<<<<<<<<<<<<<<<<

service manage

Manage service operations

sudo systemctl ${1|enable,disable,start,stop,reload,restart,status|} service

stopwatch start

start stopwatch

STOPWATCH_START_TIME=$(date +%s)

stopwatch stop

stop stopwatch

STOPWATCH_END_TIME=$(date +%s)

stopwatch elapsed

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 seconds

sleep

sleep for a specified amount of time (s: second, m: minute, h: hour, d: day)

sleep 30${2|s,m,h,d|}

timeout

Run command within a time frame

timeout seconds command

fn banner simple

function: 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
}

fx banner simple

call banner_simple function

banner_simple "my title"

fn banner color

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
}

fx banner color

call banner_color function

banner_color ${1|black,red,green,yellow,blue,magenta,cyan,white|} "my title"

fn import

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
}

fx import

call import function, to import functions from other shellscript files located in a directory (default: lib) relative to current script file

import "libname"

fn options

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
}

fx options

call options function

options=("one" "two" "three")
chooseOption "Choose:" 1 "${options[@]}"; choice=$?
echo "${options[$choice]}" selected

fn scan

Scan 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
}

fx scan

call scan function to scan a host over a port range

scan ${1|tcp,udp|} host fromPort  toPort