Essential Bash Scripts for System Monitoring and Automation
This guide presents a collection of practical Bash snippets for Linux administrators, covering random string generation, colored output, batch user creation, package and service checks, host ping testing, CPU/memory/disk monitoring, remote disk usage, website availability, and MySQL replication status verification.
This article provides a toolbox of reusable Bash scripts aimed at common Linux operations and monitoring tasks.
General Guidelines
Start scripts with the interpreter line #!/bin/bash.
Use four spaces for indentation and add comments to explain each step.
Variable naming convention: uppercase for global constants, lowercase for locals, function names in lowercase describing their purpose.
Variables are global by default; use local inside functions to avoid scope pollution.
Debugging helpers: set -e to abort on non‑zero exit codes and set -x to trace command execution.
Always test scripts in a safe environment before deploying to production.
1. Generate Random Strings or Numbers
Three methods are shown for an 8‑character random string:
# echo $RANDOM | md5sum | cut -c 1-8
# openssl rand -base64 4
# cat /proc/sys/kernel/random/uuid | cut -c 1-8For an 8‑digit random number:
# echo $RANDOM | cksum | cut -c 1-8
# openssl rand -base64 4 | cksum | cut -c 1-8
# date +%N | cut -c 1-8 cksumprints the CRC checksum and byte count.
2. Colored Output Function
A reusable function echo_color prints text in green or red using ANSI escape codes. Two implementations are provided – an if/elif version and a case version.
function echo_color() {
if [ "$1" == "green" ]; then
echo -e "[32;40m$2[0m"
elif [ "$1" == "red" ]; then
echo -e "[31;40m$2[0m"
else
echo "Usage: echo_color red|green string"
fi
}3. Batch Create Users
#!/bin/bash
DATE=$(date +%F_%T)
USER_FILE=user.txt
# Backup existing file
if [ -s "$USER_FILE" ]; then
mv "$USER_FILE" "${USER_FILE}-${DATE}.bak"
echo_color green "${USER_FILE} exists, renamed to ${USER_FILE}-${DATE}.bak"
fi
echo -e "User\tPassword" >> "$USER_FILE"
echo -e "----------------" >> "$USER_FILE"
for USER in user{1..10}; do
if ! id "$USER" &>/dev/null; then
PASS=$(echo $RANDOM | md5sum | cut -c 1-8)
useradd "$USER"
echo "$PASS" | passwd --stdin "$USER" &>/dev/null
echo -e "$USER\t$PASS" >> "$USER_FILE"
echo "$USER User create successful."
else
echo_color red "$USER User already exists!"
fi
done4. Check If a Package Is Installed
#!/bin/bash
if rpm -q sysstat &>/dev/null; then
echo "sysstat is already installed."
else
echo "sysstat is not installed!"
fi5. Verify Service Status
#!/bin/bash
PORT_C=$(ss -anu | grep -c 123)
PS_C=$(ps -ef | grep ntpd | grep -v grep)
if [ $PORT_C -eq 0 -o $PS_C -eq 0 ]; then
echo "Content" | mail -s "Subject" [email protected]
fi6. Host Liveness Check (Ping)
Three approaches are illustrated: using an array of error IPs, a counter variable, and a function that returns on success.
# Example using an array
IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
for IP in $IP_LIST; do
NUM=1
while [ $NUM -le 3 ]; do
if ping -c 1 $IP &>/dev/null; then
echo "$IP Ping is successful."
break
else
FAIL_COUNT[$NUM]=$IP
let NUM++
fi
done
if [ ${#FAIL_COUNT[*]} -eq 3 ]; then
echo "${FAIL_COUNT[1]} Ping is failure!"
unset FAIL_COUNT[*]
fi
done7. CPU, Memory, and Disk Utilization Monitoring
CPU
#!/bin/bash
DATE=$(date +%F_%H:%M)
IP=$(ifconfig eth0 | awk -F '[ :]+' '/inet addr/{print $4}')
MAIL="[email protected]"
if ! which vmstat &>/dev/null; then
echo "vmstat command not found, please install procps package."
exit 1
fi
US=$(vmstat | awk 'NR==3{print $13}')
SY=$(vmstat | awk 'NR==3{print $14}')
USE=$((US+SY))
if [ $USE -ge 50 ]; then
echo -e "Date: $DATE
Host: $IP
Problem: CPU utilization $USE" | mail -s "CPU Monitor" $MAIL
fiMemory
#!/bin/bash
DATE=$(date +%F_%H:%M)
IP=$(ifconfig eth0 | awk -F '[ :]+' '/inet addr/{print $4}')
MAIL="[email protected]"
TOTAL=$(free -m | awk '/Mem/{print $2}')
USE=$(free -m | awk '/Mem/{print $3-$6-$7}')
FREE=$((TOTAL-USE))
if [ $FREE -lt 1024 ]; then
echo -e "Date: $DATE
Host: $IP
Problem: Total=$TOTAL, Use=$USE, Free=$FREE" | mail -s "Memory Monitor" $MAIL
fiDisk
#!/bin/bash
DATE=$(date +%F_%H:%M)
IP=$(ifconfig eth0 | awk -F '[ :]+' '/inet addr/{print $4}')
MAIL="[email protected]"
TOTAL=$(fdisk -l | awk -F '[: ]+' 'BEGIN{OFS="="}/^Disk \/dev/{printf "%s=%sG,",$2,$3}')
PART_USE=$(df -h | awk 'BEGIN{OFS="="}/^\/dev/{print $1,int($5),$6}')
for i in $PART_USE; do
PART=$(echo $i | cut -d"=" -f1)
USE=$(echo $i | cut -d"=" -f2)
MOUNT=$(echo $i | cut -d"=" -f3)
if [ $USE -gt 80 ]; then
echo -e "Date: $DATE
Host: $IP
Total: $TOTAL
Problem: $PART=$USE% ($MOUNT)" | mail -s "Disk Monitor" $MAIL
fi
done8. Remote Disk Usage Monitoring
#!/bin/bash
HOST_INFO=host.info
for IP in $(awk '/^[^#]/{print $1}' $HOST_INFO); do
USER=$(awk -v ip=$IP '$1==ip{print $2}' $HOST_INFO)
PORT=$(awk -v ip=$IP '$1==ip{print $3}' $HOST_INFO)
TMP_FILE=/tmp/disk.tmp
ssh -p $PORT $USER@$IP "df -h" > $TMP_FILE
USE_RATE_LIST=$(awk 'BEGIN{OFS="="}/^\/dev/{print $1,int($5)}' $TMP_FILE)
for USE_RATE in $USE_RATE_LIST; do
PART_NAME=${USE_RATE%=*}
RATE=${USE_RATE#*=}
if [ $RATE -ge 80 ]; then
echo "Warning: $PART_NAME Partition usage $RATE%!"
fi
done
done9. Website Availability Check
Single Check
check_url() {
HTTP_CODE=$(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $1)
if [ $HTTP_CODE -ne 200 ]; then
echo "Warning: $1 Access failure!"
fi
}
# Usage: check_url www.baidu.comThree‑Attempt Check
#!/bin/bash
check_url() {
HTTP_CODE=$(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $1)
if [ $HTTP_CODE -eq 200 ]; then
return 0
else
return 1
fi
}
URL_LIST="www.baidu.com www.agasgf.com"
for URL in $URL_LIST; do
FAIL_COUNT=0
for i in {1..3}; do
if check_url $URL; then
break
else
let FAIL_COUNT++
fi
done
if [ $FAIL_COUNT -eq 3 ]; then
echo "Warning: $URL Access failure!"
fi
done10. MySQL Master‑Slave Synchronization Status
#!/bin/bash
USER=bak
PASSWD=123456
IO_SQL_STATUS=$(mysql -u$USER -p$PASSWD -e "show slave status" | awk -F: '/Slave_.*_Running/{gsub(": ",":");print $0}')
for i in $IO_SQL_STATUS; do
THREAD_STATUS_NAME=${i%:*}
THREAD_STATUS=${i#*:}
if [ "$THREAD_STATUS" != "Yes" ]; then
echo "Error: MySQL Master‑Slave $THREAD_STATUS_NAME status is $THREAD_STATUS!"
fi
doneThese scripts are intended as practical examples for interview preparation and daily operations; copying without understanding will not lead to mastery.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
