Essential Bash Scripts for System Monitoring, User Management, and Automation
This article provides a collection of practical Bash scripts for generating random strings, colorized output, batch user creation, package and service checks, host ping monitoring, CPU/memory/disk utilization alerts, website availability testing, and MySQL replication status verification, all useful for Linux system administration and interview preparation.
1 Generate Random String or Number
Generate a random 8‑character string:
# Method 1:
# echo $RANDOM | md5sum | cut -c 1-8
# Method 2:
# openssl rand -base64 4
# Method 3:
# cat /proc/sys/kernel/random/uuid | cut -c 1-8Generate a random 8‑digit number:
# Method 1:
# echo $RANDOM | cksum | cut -c 1-8
# Method 2:
# openssl rand -base64 4 | cksum | cut -c 1-8
# Method 3:
# date +%N | cut -c 1-8 cksumprints a CRC checksum and byte count.
2 Define a Color Output Function
# Method 1:
function echo_color() {
if [ $1 == "green" ]; then
echo -e "[32;40m$2[0m"
elif [ $1 == "red" ]; then
echo -e "[31;40m$2[0m"
fi
}
# Method 2:
function echo_color() {
case $1 in
green) echo -e "[32;40m$2[0m" ;;
red) echo -e "[31;40m$2[0m" ;;
*) echo "Example: echo_color red string" ;;
esac
}
# Usage example:
# echo_color green "test"The function keyword can be used with or without the word function.
3 Batch Create Users
#!/bin/bash
DATE=$(date +%F_%T)
USER_FILE=user.txt
echo_color(){
if [ $1 == "green" ]; then
echo -e "[32;40m$2[0m"
elif [ $1 == "red" ]; then
echo -e "[31;40m$2[0m"
fi
}
# Backup existing user file
if [ -s $USER_FILE ]; then
mv $USER_FILE ${USER_FILE}-${DATE}.bak
echo_color green "$USER_FILE exist, rename ${USER_FILE}-${DATE}.bak"
fi
echo -e "User Password" >> $USER_FILE
echo "----------------" >> $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 $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 Check Service Status
#!/bin/bash
PORT_C=$(ss -anu | grep -c 123)
PS_C=$(ps -ef | grep ntpd | grep -vc grep)
if [ $PORT_C -eq 0 -o $PS_C -eq 0 ]; then
echo "content" | mail -s "subject" [email protected]
fi6 Verify Host Liveness
Method 1 – store failing IPs in an array and retry three times:
#!/bin/bash
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
doneMethod 2 – count failures in a variable:
#!/bin/bash
IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
for IP in $IP_LIST; do
FAIL_COUNT=0
for ((i=1;i<=3;i++)); do
if ping -c 1 $IP >/dev/null; then
echo "$IP Ping is successful."
break
else
let FAIL_COUNT++
fi
done
if [ $FAIL_COUNT -eq 3 ]; then
echo "$IP Ping is failure!"
fi
doneMethod 3 – use a function to break out of the loop when ping succeeds:
#!/bin/bash
ping_success_status() {
if ping -c 1 $IP >/dev/null; then
echo "$IP Ping is successful."
continue
fi
}
IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
for IP in $IP_LIST; do
ping_success_status
ping_success_status
ping_success_status
echo "$IP Ping is failure!"
done7 Monitor CPU, Memory, and Disk Utilization
CPU – use vmstat to get usage and send an email if utilization exceeds 50%:
#!/bin/bash
DATE=$(date +%F" "%H:%M)
IP=$(ifconfig eth0 | awk -F '[ :]+' '/inet addr/{print $4}') # CentOS6 only
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 – alert when free memory is less than 1 GB:
#!/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 – send a warning if any partition usage exceeds 80%:
#!/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 Batch Host Disk Utilization Monitoring
Prerequisite: password‑less SSH between monitoring and target hosts. Store host connection info (IP User Port) in a file and iterate:
#!/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%=*}
USE_RATE=${USE_RATE#*=}
if [ $USE_RATE -ge 80 ]; then
echo "Warning: $PART_NAME Partition usage $USE_RATE%!"
fi
done
done9 Check Website Availability
Method 1 – single request using curl:
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
}Method 2 – using wget in spider mode:
check_url() {
if ! wget -T 10 --tries=1 --spider $1 >/dev/null 2>&1; then
echo "Warning: $1 Access failure!"
fi
}Usage example: check_url www.baidu.com Method 1 for three attempts – loop and break on success:
#!/bin/bash
check_url() {
HTTP_CODE=$(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $1)
if [ $HTTP_CODE -eq 200 ]; then
continue
fi
}
URL_LIST="www.baidu.com www.agasgf.com"
for URL in $URL_LIST; do
check_url $URL
check_url $URL
check_url $URL
echo "Warning: $URL Access failure!"
doneMethod 2 – count failures in a variable:
#!/bin/bash
URL_LIST="www.baidu.com www.agasgf.com"
for URL in $URL_LIST; do
FAIL_COUNT=0
for ((i=1;i<=3;i++)); do
HTTP_CODE=$(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $URL)
if [ $HTTP_CODE -ne 200 ]; then
let FAIL_COUNT++
else
break
fi
done
if [ $FAIL_COUNT -eq 3 ]; then
echo "Warning: $URL Access failure!"
fi
doneMethod 3 – store failures in an array:
#!/bin/bash
URL_LIST="www.baidu.com www.agasgf.com"
for URL in $URL_LIST; do
NUM=1
while [ $NUM -le 3 ]; do
HTTP_CODE=$(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $URL)
if [ $HTTP_CODE -ne 200 ]; then
FAIL_COUNT[$NUM]=$URL
let NUM++
else
break
fi
done
if [ ${#FAIL_COUNT[*]} -eq 3 ]; then
echo "Warning: $URL Access failure!"
unset FAIL_COUNT[*]
fi
done10 Check 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 Bash script examples are practical for interviews and daily operations; hands‑on practice is essential for mastering them.
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.
Efficient Ops
This public account is maintained by Xiaotianguo and friends, regularly publishing widely-read original technical articles. We focus on operations transformation and accompany you throughout your operations career, growing together happily.
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.
