Bash & Shell

Variables

Positional arguments

Stand Input

read test
echo $test

Output/Input redirection (Streams)

Test operators

[ hello = hello ]
echo $? # 0

[ 1 = 0 ]
echo $? # 1

[ 1 -eq 1]
echo $? # 0

[ -f ~/.zshrc]

[ -d ~/.kube]

If/Elif/Else

if [ ${1,,} = first ]; then
	echo "FIRST"
elif [ ${1,,} = second ]; then
	echo "SECOND"
else
	echo "NONE"
fi

# use the command to check the command exists
if command -v $command; then
	echo $command exists
else
	echo $command does not exists
fi

${1,,} is parameter expansion, allowing to ignore UPPER and lowercase when comparing the string

Case statements

case ${1,,} in
	first | second)
		echo "FIRST or SECOND"
		;;
	three)
		echo "THREE"
		;;
	*)
		echo "NONE"
esac

Arrays

NUMBER_LIST=(one two three four five)

echo $NUMBER_LIST # one
echo ${NUMBER_LIST[@]} # one two three four five
echo ${NUMBER_LIST[0]} # one

For Loop

for item in ${NUMBER_LIST[@]}; do
	echo -n $item;
done

for number in 1 2 3 4 5; do
	echo $number
done

for number in {1..10}; do
	echo $number
done

for file in logfiles/*.log; do
	echo $file
done

While Loop

myvar=1

while [ $myvar -le 10]
do
	echo $myvar
	myvar=$(( $myvar +1))
	sleep 0.5
done

Functions

# Basic function
show_uptime() {
	up=$(uptime -p | cut -c4-)
	since=$(uptime -s)
	cat << EOF
-----
This machine has been up for ${up}
It has been running since ${since}
----
EOF
}
show_uptime

# Function with args and return value
show_name(){
	echo hello $1
	if [ ${1,,} = true ]; then
		return 0
	else
		return 1
	fi
}
show_name $1
if [ $? = 0 ]; then
	echo "TRUE"
fi

Exit Code

Math

expr 30 + 10 # 40
expr 30 \* 10 # 300

Scheduling Jobs

Command-line tools

Read

read test
echo $testt

At

at 15:30 -f ./script.sh

# List the jobs in the queue
atq

# Remove the job
atrm $ID

Date

date # Sun Jun 30 14:49:57 +07 2024

Crontab

# edit the crontab file
crontab -e

# 0 5 * * 1 <command>

Test

test 10 -eq 10

Cut

echo "123456789" | cut -c2,7 # 27
echo "123456789" | cut -c2-7 # 234567
echo "123456789" | cut -c5- # 56789
echo "123456789" | cut -c-4 # 1234

AWK

awk '{print $1}' file.txt # one
awk '{print $2}' file.txt # two

# read from csv
awk -F, '{print $1}' file.csv

SED

sed 's/one/two/g' file.txt # replace "one" to "two"
sed -i.ORIGINAL 's/one/two/g' file.txt # save "file.txt.ORIGINAL" before change

References