Operations 23 min read

Essential Bash Scripts for Linux Engineers: From Games to System Monitoring

This article compiles a collection of practical Bash scripts for Linux engineers, covering interactive games, network connection checks, process management, system monitoring, file operations, user account handling, and automated backups, each presented with clear explanations and ready-to-use code examples.

Open Source Linux
Open Source Linux
Open Source Linux
Essential Bash Scripts for Linux Engineers: From Games to System Monitoring

As a Linux engineer, well‑written scripts can boost productivity and free up time for other tasks. Below is a curated list of useful Bash scripts, each accompanied by a brief description and the full source code.

(1) User Guesses a Number

A script generates a random number between 1 and 100, prompts the user to guess, and provides feedback until the correct guess is made.

#!/bin/bash
# Generate a random number between 1‑100
num=$[RANDOM%100+1]
while :
do
  read -p "Computer generated a number 1‑100, you guess: " guess
  if [ $guess -eq $num ]; then
    echo "Congratulations, you guessed correctly"
    exit
  elif [ $guess -gt $num ]; then
    echo "Oops, too high"
  else
    echo "Oops, too low"
  fi
done

(2) Count Remote IP Connections

Counts how many distinct remote IP addresses are currently connected to the host (SSH, web, FTP, etc.).

#!/bin/bash
netstat -atn | awk '{print $5}' | awk -F: '{print $1}' | sort -nr | uniq -c

(3) Hello World Function

Defines a simple function that prints "Hello world!" and calls it.

#!/bin/bash
function example {
  echo "Hello world!"
}
example

(4) Print Tomcat PID

Finds the PID of a Tomcat process and prints it.

#!/bin/sh
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

Implements a command‑line rock‑paper‑scissors game against the computer.

#!/bin/bash
game=(石头 剪刀 布)
num=$[RANDOM%3]
computer=${game[$num]}

echo "Choose your move:"
echo "1. 石头"
echo "2. 剪刀"
echo "3. 布"
read -p "Please enter 1‑3: " person
case $person in
  1) if [ $num -eq 0 ]; then echo "Tie"; elif [ $num -eq 1 ]; then echo "You win"; else echo "Computer wins"; fi ;;
  2) if [ $num -eq 0 ]; then echo "Computer wins"; elif [ $num -eq 1 ]; then echo "Tie"; else echo "You win"; fi ;;
  3) if [ $num -eq 0 ]; then echo "You win"; elif [ $num -eq 1 ]; then echo "Computer wins"; else echo "Tie"; fi ;;
  *) echo "Please input a number between 1‑3";;
esac

(6) Multiplication Table (9×9)

Prints the classic 9×9 multiplication table.

#!/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

Downloads, compiles, and installs Memcached.

#!/bin/bash
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) Detect Superuser and Install vsftpd

Checks if the current user is root; if so, installs vsftpd, otherwise prints a warning.

#!/bin/bash
if [ "$USER" == "root" ]; then
  yum -y install vsftpd
else
  echo "You are not an administrator, cannot install software"
fi

(9) If‑Expression Demo

Demonstrates a series of conditional checks based on the first script argument.

#!/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

Finds the Tomcat PID, kills it, cleans work directory, and restarts the service.

#!/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

Uses ANSI escape codes to display an 8×8 chessboard with alternating colors.

#!/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

Counts how many entries in /etc/passwd have a login shell (bash).

#!/bin/bash
grep "bash$" /etc/passwd | wc -l
# or using awk
awk '/bash$/{x++} END{print x}' /etc/passwd

(14) Backup MySQL Table Data

Loads data from a local file into a MySQL table with timestamps.

#!/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 0

(15) Real‑Time eth0 Traffic Monitor

Continuously displays received and transmitted packet counts on interface ens33.

#!/bin/bash
while :; do
  echo "Local interface ens33 traffic:" 
  ifconfig ens33 | grep "RX packets" | awk '{print $5}'
  ifconfig ens33 | grep "TX packets" | awk '{print $5}'
  sleep 1
done

(16) Scan 192.168.4.0/24 for Live Hosts

Pings each address in the subnet and reports whether it is up or down.

#!/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 and Set Password

Prompts for a username and password, creates the account, and assigns the password (default 123456 if none entered).

#!/bin/bash
read -p "Enter username: " user
if [ -z $user ]; then
  echo "Username is required"
  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

Prompts for three integers and outputs them in ascending order.

#!/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 (small to large): $num1,$num2,$num3"

(19) Time‑Based Greeting Script

Displays a greeting according to the current hour and prints the full timestamp.

#!/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 a File

Creates a file and appends the string "I lov cls".

#!/bin/bash
cd /home/wenmin/
touch wenxing.txt
echo "I lov cls" >> wenxing.txt

(21) Simple For‑Loop Summation

Calculates the sum of numbers 1‑99 and demonstrates nested loops.

#!/bin/bash
s=0
for ((i=1;i<100;i++)); do
  s=$((s+i))
  echo $i
done
echo $s

(22) Iterate Over Script Arguments

Prints each argument prefixed with a custom message.

#!/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

Creates a dated tar.gz archive of /var/log every Friday at 03:00.

#!/bin/bash
tar -czf log-`date +%Y%m%d`.tar.gz /var/log
# Add to crontab: 00 03 * * 5 /home/wenmin/datas/logbak.sh

(24) Simple Sum and Division Functions

Defines two functions: one for addition, another for integer division, and demonstrates their use.

#!/bin/bash
function sum() { echo $(( $1 + $2 )); }
read -p "input your parameter " p1
read -p "input your parameter " p2
sum $p1 $p2
function multi() { echo $(( $1 / $2 )); }
read -p "input your parameter " x1
read -p "input your parameter " x2
multi $x1 $x2
let v3=$((1+2))
echo $v3

(25) Case‑Statement Demo

Prints a different string based on the first command‑line argument.

#!/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 Auto‑Monitor and Restart

Monitors a Tomcat service, checks HTTP response code, and restarts the process if it is down.

#!/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] HTTP 200 – Tomcat is running"
    else
      echo "[error] HTTP $TomcatServiceCode – restarting Tomcat"
      kill -9 $TomcatID
      sleep 3
      $StartTomcat
    fi
  else
    echo "[error] Tomcat process not found – starting"
    $StartTomcat
  fi
  echo "------------------------------"
}
Monitor >> $TomcatMonitorLog

(27) Create Linux User with Positional Parameters

Uses $1 as username and $2 as password to create a new account.

#!/bin/bash
useradd "$1"
echo "$2" | passwd --stdin "$1"

(28) Show Script Arguments

Prints the script name and first three arguments, then displays the argument count and list.

#!/bin/bash
echo "$0 $1 $2 $3"
echo "$#"
echo "$@"
echo "$*"

(29) Resource‑Alert Script

Sends an email to root when free memory < 500 MiB or root partition free space < 1 GiB.

#!/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, resource shortage detected.
EOF
  fi
done

(30) Check File Existence

Verifies whether a specific file exists.

#!/bin/bash
if [ -f /home/wenmin/datas ]; then
  echo "File exists"
fi

(31) While‑Loop Summation (1‑100)

Calculates the sum of numbers from 1 to 100 using a while loop.

#!/bin/bash
s=0
i=1
while [ $i -le 100 ]; do
  s=$((s + i))
  i=$((i + 1))
 done
echo $s

(32) One‑Click LNMP Deployment (RPM)

Installs Apache, MariaDB, and PHP on CentOS 7/RHEL 7.

#!/bin/bash
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) Interactive Parameter Input

Prompts the user for name, age, friend, and love with timeouts, then echoes each value.

#!/bin/bash
read -t 7 -p "input your name " NAME
echo $NAME
read -t 11 -p "input your 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 Script

Copies a source file to a destination.

#!/bin/bash
cp $1 $2

(35) File Existence Test

Checks if a file named file.txt exists and prints the result.

#!/bin/bash
if [ -f file.txt ]; then
  echo "File exists"
else
  echo "File does not exist"
fi

These scripts provide a practical toolbox for Linux system administrators and developers, illustrating common tasks such as user interaction, process control, monitoring, file manipulation, and service automation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

SysadminBackupBashShell scripting
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.