Collection of Useful Bash Scripts for Linux Engineers
This article compiles a variety of practical Bash scripts for Linux engineers, covering tasks such as number guessing games, network monitoring, process management, user account handling, file operations, system resource checks, and automated service deployments, providing ready-to-use code snippets for everyday sysadmin automation.
As a Linux engineer, well‑written scripts can boost productivity and free up time for other tasks; this article gathers a set of useful Bash scripts for common administrative operations.
(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
done(2) 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 -c(3) Hello World Function
#!/bin/bash
function example {
echo "Hello world!"
}
example(4) 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 $pidlist
echo "tomcat Id list :$pidlist"(5) Rock‑Paper‑Scissors Game
#!/bin/bash
game=(石头 剪刀 布)
num=$[RANDOM%3]
computer=${game[$sum]}
# ... (rest of the case logic) ...(6) Multiplication Table (9×9)
#!/bin/bash
for i in `seq 9`
do
for j in `seq $i`
do
echo -n "$j*$i=$[i*j] "
done
echo
done(7) 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 install(8) Check if Current User Is Root
#!/bin/bash
if [ $USER == "root" ]; then
yum -y install vsftpd
else
echo "You are not an administrator, no permission to install software"
fi(9) 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"
fi(11) Kill and Restart Tomcat Process
#!/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:"
echo "service stop success"
echo "start tomcat"
cd /opt/apache-tomcat-7.0.75
rm -rf work/*
cd bin
./startup.sh(12) Print Chessboard Pattern
#!/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
done(13) Count Login‑Capable Accounts
#!/bin/bash
# Method 1
grep "bash$" /etc/passwd | wc -l
# Method 2
awk -F: '/bash$/{x++}END{print x}' /etc/passwd(14) Backup MySQL Table Data
#!/bin/sh
source /etc/profile
dbName=mysql
tableName=db
echo [`date +'%Y-%m-%d %H:%M:%S'`] 'start loading data...'
mysql -uroot -proot -P3306 ${dbName} -e "LOAD DATA LOCAL INFILE '# /home/wenmin/wenxing.txt' INTO TABLE ${tableName} FIELDS TERMINATED BY ';'"
echo [`date +'%Y-%m-%d %H:%M:%S'`] 'end loading data...'
exit(15) Real‑Time eth0 Packet Flow
#!/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
done(16) 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
done(17) Create User with Password Prompt
#!/bin/bash
read -p "Enter username: " user
if [ -z $user ]; then
echo "You must enter a username"
exit 2
fi
stty -echo
read -p "Enter password: " pass
stty echo
pass=${pass:-123456}
useradd "$user"
echo "$pass" | passwd --stdin "$user"(18) 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"(19) 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"(20) Write Text to File
#!/bin/bash
cd /home/wenmin/
touch wenxing.txt
echo "I lov cls" >> wenxing.txt(21) Simple For‑Loop Summation
#!/bin/bash
s=0
for i in {1..99}
do
s=$[s+i]
done
echo $s(22) Loop Over Script Arguments
#!/bin/bash
for i in "$*"
do
echo "wenmin xihuan $i"
done
for j in "$@"
do
echo "wenmin xihuan $j"
done(23) Weekly Log Backup with tar
#!/bin/bash
# Every Friday backup /var/log
tar -czf log-`date +%Y%m%d`.tar.gz /var/log
# Add to crontab: 00 03 * * 5 /home/wenmin/datas/logbak.sh(24) 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
v1=1; v2=2; let v3=$v1+$v2; echo $v3(25) 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";;
esac(26) Tomcat Monitoring and Auto‑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]开始监控tomcat...[$(date +'%F %H:%M:%S')]"
if [ $TomcatID ]; then
echo "[info]tomcat进程ID为:$TomcatID."
TomcatServiceCode=$(curl -s -o $GetPageInfo -m 10 --connect-timeout 10 $WebUrl -w %{http_code})
if [ $TomcatServiceCode -eq 200 ]; then
echo "[info]返回码为$TomcatServiceCode, tomcat启动成功, 页面正常."
else
echo "[error]访问出错,状态码为$TomcatServiceCode, 错误日志已输出到$GetPageInfo"
echo "[error]开始重启tomcat"
kill -9 $TomcatID
sleep 3
$StartTomcat
fi
else
echo "[error]进程不存在! tomcat自动重启..."
echo "[info]$StartTomcat, 请稍候......"
$StartTomcat
fi
echo "------------------------------"
}
Monitor >> $TomcatMonitorLog(27) Create Linux User with Positional Parameters
#!/bin/bash
useradd "$1"
echo "$2" | passwd --stdin "$1"(28) Parameter Count and Display
#!/bin/bash
echo "$0 $1 $2 $3"
echo $#
echo $@
echo $*(29) Memory and Disk Space Alert
#!/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 <
(30) Check File Existence
#!/bin/bash
if [ -f /home/wenmin/datas ]; then
echo "File exists"
fi
(31) While Loop Summation Example
#!/bin/bash
s=0
i=1
while [ $i -le 100 ]
do
s=$[s+i]
i=$[i+1]
done
echo $s
echo $i
(32) One‑Click LNMP Deployment (RPM)
#!/bin/bash
# Install LNMP 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 mariadb
(33) 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 $LOVE
(34) Simple File Copy Wrapper
#!/bin/bash
cp $1 $2
(35) File Existence Test
#!/bin/bash
if [ -f file.txt ]; then
echo "文件存在"
else
echo "文件不存在"
fi
The collection demonstrates practical Bash scripting techniques for system monitoring, automation, user management, and service deployment, serving as a handy reference for Linux administrators.IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
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.