30 Essential Bash Scripts Every Linux Engineer Should Master
This article compiles a comprehensive collection of practical Bash scripts—from a number‑guessing game and remote IP counting to system monitoring, user management, and one‑click LNMP deployment—providing Linux engineers with ready‑to‑use tools that boost productivity and automate routine tasks.
As a Linux engineer, writing good scripts not only improves work efficiency but also frees up time for other activities. Below is a curated list of useful Bash scripts for various administrative tasks.
(1) User Guess Number
<code>#!/bin/bash
# Generate a random number between 1 and 100 and prompt the user to guess it
num=$[RANDOM%100+1]
echo "$num"
while :
do
read -p "计算机生成了一个 1‑100 的随机数,你猜: " cai
if [ $cai -eq $num ]; then
echo "恭喜,猜对了"
exit
elif [ $cai -gt $num ]; then
echo "Oops,猜大了"
else
echo "Oops,猜小了"
fi
done
</code>(2) Count Remote IP Connections
<code>#!/bin/bash
# List remote IPs connecting to the machine (ssh, web, ftp, etc.)
netstat -atn | awk '{print $5}' | awk -F: '{print $1}' | sort -nr | uniq -c
</code>(3) Hello World
<code>#!/bin/bash
function example {
echo "Hello world!"
}
example
</code>(4) Print Tomcat PID
<code>#!/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"
</code>(5) Rock‑Paper‑Scissors Game
<code>#!/bin/bash
game=(石头 剪刀 布)
num=$[RANDOM%3]
computer=${game[$num]}
echo "请根据下列提示选择您的出拳手势"
echo " 1. 石头"
echo " 2. 剪刀"
echo " 3. 布 "
read -p "请选择 1-3 :" person
case $person in
1)
if [ $num -eq 0 ]; then echo "平局"; elif [ $num -eq 1 ]; then echo "你赢"; else echo "计算机赢"; fi;;
2)
if [ $num -eq 0 ]; then echo "计算机赢"; elif [ $num -eq 1 ]; then echo "平局"; else echo "你赢"; fi;;
3)
if [ $num -eq 0 ]; then echo "你赢"; elif [ $num -eq 1 ]; then echo "计算机赢"; else echo "平局"; fi;;
*) echo "必须输入1-3 的数字";;
esac
</code>(6) Multiplication Table (9×9)
<code>#!/bin/bash
for i in `seq 9`; do
for j in `seq $i`; do
echo -n "$j*$i=$[i*j] "
done
echo
done
</code>(7) Install Memcached from Source
<code>#!/bin/bash
# One‑click deploy 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
</code>(8) Check If Current User Is Root
<code>#!/bin/bash
if [ $USER == "root" ]; then
yum -y install vsftpd
else
echo "您不是管理员,没有权限安装软件"
fi
</code>(9) Simple If Expression Demo
<code>#!/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
</code>(11) Kill and Restart Tomcat
<code>#!/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
</code>(12) Print Chessboard Pattern
<code>#!/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
</code>(13) Count Login‑Capable Accounts
<code>#!/bin/bash
# Method 1
grep "bash$" /etc/passwd | wc -l
# Method 2
awk '/bash$/{x++}END{print x}' /etc/passwd
</code>(14) Backup MySQL Table Data
<code>#!/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
EOF
</code>(15) Real‑Time eth0 Traffic Monitor
<code>#!/bin/bash
while :
do
echo '本地网卡 ens33 流量信息如下:'
ifconfig ens33 | grep "RX pack" | awk '{print $5}'
ifconfig ens33 | grep "TX pack" | awk '{print $5}'
sleep 1
done
</code>(16) Ping Scan of 192.168.4.0/24
<code>#!/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
</code>(17) Create User with Password
<code>#!/bin/bash
read -p "请输入用户名:" user
if [ -z $user ]; then echo "您不需要输入账户名"; exit 2; fi
stty -echo
read -p "请输入密码:" pass
stty echo
pass=${pass:-123456}
useradd "$user"
echo "$pass" | passwd --stdin "$user"
</code>(18) Sort Three Integers
<code>#!/bin/bash
read -p " 请输入一个整数:" num1
read -p " 请输入一个整数:" num2
read -p " 请输入一个整数: " num3
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 "排序后数据(从小到大)为:$num1,$num2,$num3"
</code>(19) Time‑Based Greeting Script
<code>#!/bin/bash
# Greet based on current time
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 "当前时间是:$(date +"%%Y-%%m-%%d %%H:%%M:%%S")"
echo -e "\033[34m$msg\033[0m"
</code>(20) Write Text to File
<code>#!/bin/bash
cd /home/wenmin/
touch wenxing.txt
echo "I lov cls" >>wenxing.txt
</code>(21) For‑Loop Summation
<code>#!/bin/bash
s=0
for ((i=1;i<100;i++)); do
s=$[s+i]
done
echo $s
</code>(22) Loop Over Arguments
<code>#!/bin/bash
for i in "$*"; do
echo "wenmin xihuan $i"
done
for j in "$@"; do
echo "wenmin xihuan $j"
done
</code>(23) Weekly Log Backup with tar
<code>#!/bin/bash
# Backup /var/log every Friday
tar -czf log-`date +%Y%m%d`.tar.gz /var/log
# Add to crontab: 00 03 * * 5 /home/wenmin/datas/logbak.sh
</code>(24) Simple Sum and Division Functions
<code>#!/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
</code>(25) Case‑Statement Demo
<code>#!/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
</code>(26) Tomcat Auto‑Monitor and Restart
<code>#!/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自动重启..."
$StartTomcat
fi
echo "------------------------------"
}
Monitor >> $TomcatMonitorLog
</code>(27) Create Linux User via Positional Parameters
<code>#!/bin/bash
useradd "$1"
echo "$2" | passwd --stdin "$1"
</code>(28) Show Passed Arguments
<code>#!/bin/bash
echo "$0 $1 $2 $3" #传入三个参数
echo $# #获取传入参数的数量
echo $@ #打印获取传入参数
echo $* #打印获取传入参数
</code>(29) Memory and Disk Alert
<code>#!/bin/bash
# Alert when memory <500M or root partition <1000M
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
done
</code>(30) Check File Existence
<code>#!/bin/bash
if [ -f /home/wenmin/datas ]; then
echo "File exists"
fi
</code>(31) While Loop Summation
<code>#!/bin/bash
s=0
i=1
while [ $i -le 100 ]; do
s=$[s+i]
i=$[i+1]
done
echo $s
echo $i
</code>(32) One‑Click LNMP Deployment (RPM)
<code>#!/bin/bash
# Deploy 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
</code>(33) Read Console Parameters with Timeout
<code>#!/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
</code>(34) Simple Copy Script
<code>#!/bin/bash
cp $1 $2
</code>(35) File Existence Check
<code>#!/bin/bash
if [ -f file.txt ]; then
echo "文件存在"
else
echo "文件不存在"
fi
</code>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.