Bash
Disable history file saving
Variable expansion
https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
Default values
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
Empty value checking
-z : has zero length
Parameters as array
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
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
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