Skip to content

Bash

Disable history file saving

unset HISTFILE

Variable expansion

https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

Default values

a=${parameter:=default_value}

File name

fullname="/home/john/temp/file.tar.gz"

directory=${fullname%/*}
/home/john/temp

fname=${fullname##*/}
file.tar.gz

echo ${fname##*.}
gz

echo ${fname%.*}
file.tar

Multi-line variable to string with escape sequence

message="$@"  
message="${message//$'\r'/}"  
message="${message//$'\n'/\\n}"

Empty value checking

-z : has zero length

if [ -z $var ]
if [ -z "$var" ]
if [ ! $var ]
if [ ! "$vari" ]

Parameters as array

#!/bin/bash
cmd_options=(
  --attr 1 
  --sort 2
  --un
)
./application "${cmd_options[@]}"

Arrays

# cat domains.txt
google.com
domains.com
gmail.com
yahoo.com

# cat foo.sh
DOMAINS=$(cat domains.txt)
HTTP1=""
for domain in $DOMAINS ; do
    code=`curl -I $domain 2>/dev/null | grep ^HTTP | awk '{print $2}'`
    if [ ! -z $HTTP1 ];then
       HTTP1+="|"
    fi
    HTTP1+="$domain:$code"
done
echo $HTTP1
IFS='|'
readarray -d '|' ARR <<< $HTTP1
#
arraylength=${#ARR[@]}
for (( i=1; i<${arraylength}+1; i++ ));
do
  echo $i ${ARR[$i-1]}
done

Colors

# 16 colors
for code in {0..15}; do echo -e "\e[38;05;${code}m $code: Test"; done
# 256 colors
for code in {0..255}; do echo -e "\e[38;05;${code}m $code: Test"; done

Padding string

for output

NAME=nginx
echo -e "---------------------- [UP]\r$NAME"

for variable

my_var=$(printf %8s aaaa | tr ' ' X); echo $my_var
XXXXaaaa

my_var=$(printf %-8s aaaa | tr ' ' X); echo $my_var
aaaaXXXX

Loop forever

while :; do echo $(date) ' : ' $( YOUR COMMAND ) >> /var/log/my.log; sleep 60; done

Base path

#!/bin/bash
# set Actual working path
which realpath >/dev/null 2>&1 && BASEPATH=$(realpath $0) || { echo 'ERROR: Utility realpath not found'; exit 1 }
BASEPATH=${BASEPATH%/*}

PS1

in /etc/bash.bashrc

if [[ ${EUID} == 0 ]] ; then
  PS1='\[\033[31m\]\u\[\033[m\]@\[\033[34m\]\h:\[\033[32;1m\]\w\[\033[m\]\$ '
else
  PS1='\[\033[36m\]\u\[\033[m\]@\[\033[34m\]\h:\[\033[32;1m\]\w\[\033[m\]\$ '
fi

Prevent duplicate script call

PID_FILE=pid.file
if [ -e "$PID_FILE" ] && kill -0 $(cat "$PID_FILE") ; then
  echo "Script is already running." 
  exit 1
fi
# Save the current PID to the file
echo $$ > $PID_FILE
echo "Running script"
# ...
#
# end of logic
rm -f $PID_FILE