34 Essential Linux Bash Scripts Every Sysadmin Should Know
This article compiles a curated collection of 34 practical Bash scripts for Linux engineers, covering tasks such as number guessing games, network monitoring, user management, service control, log backup, and system health checks, providing ready‑to‑run code snippets to boost productivity and automate routine operations.
As a Linux engineer, well‑written scripts can greatly improve efficiency and free up time for other tasks. Below is a curated list of useful Bash scripts covering a wide range of system‑administration scenarios.
1. User Guess Number Game
#!/bin/bash
# Generate a random number between 1 and 100 and let the user guess it
num=$[RANDOM%100+1]
while :
do
read -p "Computer generated a number between 1‑100, you guess: " cai
if [ $cai -eq $num ]; then
echo "Congratulations, you guessed correctly"
exit
elif [ $cai -gt $num ]; then
echo "Oops, too high"
else
echo "Oops, too low"
fi
done2. Count Remote IP Connections
#!/bin/bash
# Show how many remote IPs are connected to the host (ssh, web, ftp, etc.)
netstat -atn | awk '{print $5}' | awk '{print $1}' | sort -nr | uniq -c3. Hello World Function
#!/bin/bash
function example {
echo "Hello world!"
}
example4. Print Tomcat PID
#!/bin/sh
v1="Hello"
v2="world"
v3=${v1}${v2}
echo $v3
pidlist=`ps -ef|grep apache-tomcat-7.0.75|grep -v "grep"|awk '{print $2}'`
echo "tomcat Id list :$pidlist"5. Rock‑Paper‑Scissors Game
#!/bin/bash
game=(石头 剪刀 布)
num=$[RANDOM%3]
computer=${game[$num]}
# ... (prompt user and determine win/lose)6. Multiplication Table
#!/bin/bash
for i in `seq 9`
do
for j in `seq $i`
do
echo -n "$j*$i=$[i*j] "
done
echo
done7. Install Memcached from Source
#!/bin/bash
# One‑click deployment of memcached
wget http://www.memcached.org/files/memcached-1.5.1.tar.gz
yum -y install gcc
tar -xf memcached-1.5.1.tar.gz
cd memcached-1.5.1
./configure
make
make install8. Check If Current User Is Root
#!/bin/bash
if [ $USER == "root" ]
then
yum -y install vsftpd
else
echo "You are not an administrator, cannot install software"
fi9. Simple If‑Expression Demo
#!/bin/bash -xv
if [ $1 -eq 2 ]; then
echo "wo ai wenmin"
elif [ $1 -eq 3 ]; then
echo "wo ai wenxing"
elif [ $1 -eq 4 ]; then
echo "wo de xin"
elif [ $1 -eq 5 ]; then
echo "wo de ai"
fi10. Kill and Restart Tomcat
#!/bin/bash
pidlist=`ps -ef|grep apache-tomcat-7.0.75|grep -v "grep"|awk '{print $2}'`
echo "tomcat Id list :$pidlist"
kill -9 $pidlist
echo "KILL $pidlist:"
# restart
cd /opt/apache-tomcat-7.0.75
rm -rf work/*
cd bin
./startup.sh11. Print Chessboard
#!/bin/bash
for i in {1..8}
do
for j in {1..8}
do
sum=$[i+j]
if [ $[sum%2] -eq 0 ]; then
echo -ne "\033[46m \033[0m"
else
echo -ne "\033[47m \033[0m"
fi
done
echo
done12. Count Login‑Capable Accounts
#!/bin/bash
# Method 1
grep "bash$" /etc/passwd | wc -l
# Method 2
awk -F: '/bash$/{x++}END{print x}' /etc/passwd13. Backup MySQL Table Data
#!/bin/sh
source /etc/profile
dbName=mysql
tableName=db
mysql -uroot -proot -P3306 $dbName -e "LOAD DATA LOCAL INFILE '# /home/wenmin/wenxing.txt' INTO TABLE $tableName FIELDS TERMINATED BY ';'"14. Real‑Time eth0 Traffic Monitor
#!/bin/bash
while :
do
echo 'Local interface ens33 traffic:'
ifconfig ens33 | grep "RX pack" | awk '{print $5}'
ifconfig ens33 | grep "TX pack" | awk '{print $5}'
sleep 1
done15. Scan 192.168.4.0/24 Host Status
#!/bin/bash
for i in {1..254}
do
ping -c 2 -i 0.3 -W 1 192.168.1.$i &>/dev/null
if [ $? -eq 0 ]; then
echo "192.168.1.$i is up"
else
echo "192.168.1.$i is down"
fi
done16. Create User with Password Prompt
#!/bin/bash
read -p "Enter username: " user
if [ -z $user ]; then
echo "You must provide a username"
exit 2
fi
stty -echo
read -p "Enter password: " pass
stty echo
pass=${pass:-123456}
useradd "$user"
echo "$pass" | passwd --stdin "$user"17. Sort Three Integers
#!/bin/bash
read -p "Enter first integer: " num1
read -p "Enter second integer: " num2
read -p "Enter third integer: " num3
# Simple bubble‑sort logic
if [ $num1 -gt $num2 ]; then tmp=$num1; num1=$num2; num2=$tmp; fi
if [ $num1 -gt $num3 ]; then tmp=$num1; num1=$num3; num3=$tmp; fi
if [ $num2 -gt $num3 ]; then tmp=$num2; num2=$num3; num3=$tmp; fi
echo "Sorted numbers: $num1,$num2,$num3"18. Time‑Based Greeting Script
#!/bin/bash
tm=$(date +%H)
if [ $tm -le 12 ]; then
msg="Good Morning $USER"
elif [ $tm -gt 12 -a $tm -le 18 ]; then
msg="Good Afternoon $USER"
else
msg="Good Night $USER"
fi
echo "Current time: $(date +"%Y-%m-%d %H:%M:%S")"
echo -e "\033[34m$msg\033[0m"19. Write Text to File
#!/bin/bash
cd /home/wenmin/
touch wenxing.txt
echo "I lov cls" >> wenxing.txt20. Sum Numbers with For Loop
#!/bin/bash
s=0
for ((i=1;i<100;i++))
do
s=$[s+i]
done
echo $s
# Additional loops omitted for brevity21. Iterate Over Arguments
#!/bin/bash
for i "$*"
do
echo "wenmin xihuan $i"
done
for j "$@"
do
echo "wenmin xihuan $j"
done22. Weekly Log Backup with tar
#!/bin/bash
# Run every Friday via cron
tar -czf log-`date +%Y%m%d`.tar.gz /var/log23. Sum and Division Functions
#!/bin/bash
function sum {
s=$[ $1 + $2 ]
echo $s
}
read -p "input your parameter " p1
read -p "input your parameter " p2
sum $p1 $p2
function multi {
r=$[ $1 / $2 ]
echo $r
}
read -p "input your parameter " x1
read -p "input your parameter " x2
multi $x1 $x2
let v3=$v1+$v2
echo $v324. Case‑Statement Demo
#!/bin/bash
case $1 in
1) echo "wenmin" ;;
2) echo "wenxing" ;;
3) echo "wemchang" ;;
4) echo "yijun" ;;
5) echo "sinian" ;;
6) echo "sikeng" ;;
7) echo "yanna" ;;
*) echo "danlian" ;;
esac25. Tomcat Auto‑Monitor and Restart
#!/bin/sh
TomcatID=$(ps -ef|grep tomcat|grep -w 'apache-tomcat-7.0.75'|grep -v 'grep'|awk '{print $2}')
StartTomcat=/opt/apache-tomcat-7.0.75/bin/startup.sh
WebUrl=http://192.168.254.118:8080/
GetPageInfo=/dev/null
TomcatMonitorLog=/tmp/TomcatMonitor.log
Monitor(){
echo "[info] Starting Tomcat monitor...$(date '+%F %H:%M:%S')"
if [ $TomcatID ]; then
echo "[info] Tomcat PID: $TomcatID"
TomcatServiceCode=$(curl -s -o $GetPageInfo -m 10 --connect-timeout 10 $WebUrl -w %{http_code})
if [ $TomcatServiceCode -eq 200 ]; then
echo "[info] Tomcat responded with 200, service OK"
else
echo "[error] Tomcat error $TomcatServiceCode, restarting..."
kill -9 $TomcatID
sleep 3
$StartTomcat
fi
else
echo "[error] Tomcat process not found, starting..."
$StartTomcat
fi
echo "------------------------------"
}
Monitor >> $TomcatMonitorLog26. Create Linux Account via Positional Parameters
#!/bin/bash
useradd "$1"
echo "$2" | passwd --stdin "$1"27. Show Passed Arguments
#!/bin/bash
echo "$0 $1 $2 $3"
echo $#
echo $@
echo $*28. Memory and Disk Alert Script
#!/bin/bash
disk_size=$(df / | awk '/\//{print $4}')
mem_size=$(free | awk '/Mem/{print $4}')
while :
do
if [ $disk_size -le 512000 -a $mem_size -le 1024000 ]; then
mail -s "Warning" root <<EOF
Insufficient resources, 资源不足
EOF
fi
done29. Check If File Exists
#!/bin/bash
if [ -f /home/wenmin/datas ]; then
echo "File exists"
fi30. While Loop Sum Example
#!/bin/bash
s=0
i=1
while [ $i -le 100 ]
do
s=$[s+i]
i=$[i+1]
done
echo $s
echo $i31. One‑Click LNMP (RPM) Deployment
#!/bin/bash
# Install LAMP stack on CentOS/RHEL 7
yum -y install httpd
yum -y install mariadb mariadb-devel mariadb-server
yum -y install php php-mysql
systemctl start httpd mariadb
systemctl enable httpd mariadb32. Read Console Parameters with Timeout
#!/bin/bash
read -t 7 -p "input your name " NAME
echo $NAME
read -t 11 -p "input you age " AGE
echo $AGE
read -t 15 -p "input your friend " FRIEND
echo $FRIEND
read -t 16 -p "input your love " LOVE
echo $LOVE33. Simple Copy Script
#!/bin/bash
cp $1 $234. File Existence Check
#!/bin/bash
if [ -f file.txt ]; then
echo "文件存在"
else
echo "文件不存在"
fiThe collection demonstrates how Bash can be leveraged for everyday Linux system tasks, offering ready‑to‑use snippets that can be adapted or extended for production environments.
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
