Fundamentals 8 min read

7 Practical Shell Script Examples to Boost Your Linux Automation Skills

This article presents seven ready‑to‑use Bash scripts that demonstrate parallel host querying, process statistics gathering, file renaming, directory management, log analysis, network request monitoring, and file size sorting, each with complete code and step‑by‑step explanations.

Liangxu Linux
Liangxu Linux
Liangxu Linux
7 Practical Shell Script Examples to Boost Your Linux Automation Skills

Script 1: Parallel hostname retrieval and fastest CPU info

The script runs SSH commands on multiple hosts concurrently, records how long each hostname lookup takes, writes the timings to hostname.txt, then selects the host with the shortest duration and displays its current CPU usage via top.

#!/bin/bash
ALL_HOSTS=(IP1 IP2 IP3)  # replace with actual IP addresses
for host in ${ALL_HOSTS[*]}; do
{
    start_time=$(date +'%s')
    ssh $host "hostname" >/dev/null
    sleep 2
    stop_time=$(date +'%s')
    time_consuming=$((stop_time-start_time))
    echo "$host: $time_consuming" >>hostname.txt
}&
 done
wait
host=$(sort -n -k 2 hostname.txt | head -1 | awk -F':' '{print $1}')
ssh $host "top -b -n 1"

Script 2: Process state statistics and zombie cleanup

This script scans /proc to count total, running, stopped, sleeping, and zombie processes, writes all zombie PIDs to zombie.txt, and kills each zombie.

#!/bin/bash
ALL_PROCESS=$(ls /proc/ | egrep '[0-9]+')
running_count=0
stoped_count=0
sleeping_count=0
zombie_count=0
for pid in ${ALL_PROCESS[*]}; do
    test -f /proc/$pid/status && state=$(egrep "State" /proc/$pid/status | awk '{print $2}')
    case "$state" in
        R) running_count=$((running_count+1)) ;;
        T) stoped_count=$((stoped_count+1)) ;;
        S) sleeping_count=$((sleeping_count+1)) ;;
        Z) zombie_count=$((zombie_count+1))
           echo "$pid" >>zombie.txt
           kill -9 "$pid"
           ;;
    esac
done

echo -e "total: $((running_count+stoped_count+sleeping_count+zombie_count))
running: $running_count
stoped: $stoped_count
sleeping: $sleeping_count
zombie: $zombie_count"

Script 3: Rename ".sh" files to ".shell" and delete the second line

The script finds every ".sh" file under the current directory, renames it to ".shell", and removes the second line of each renamed file.

#!/bin/bash
ALL_SH_FILE=$(find . -type f -name "*.sh")
for file in ${ALL_SH_FILE[*]}; do
    filename=$(echo $file | awk -F'.sh' '{print $1}')
    new_filename="${filename}.shell"
    mv "$file" "$new_filename"
    sed -i '2d' "$new_filename"
 done

Script 4: Periodic jstack capture with directory rotation

This script ensures /tmp/jstack exists (clearing it if it already does), then every hour captures a jstack dump of the inceptor Java process, names the file with the current timestamp, and keeps at most ten files by deleting the oldest.

#!/bin/bash
DIRPATH='/tmp/jstack'
CURRENT_TIME=$(date +'%F-%H:%M:%S')
if [ ! -d "$DIRPATH" ]; then
    mkdir "$DIRPATH"
else
    rm -rf "$DIRPATH"/*
fi
cd "$DIRPATH"
while true; do
    sleep 3600
    pid=$(ps -ef | grep 'inceptor' | grep -v grep | awk '{print $2}')
    jstack $pid >> "jstack_${CURRENT_TIME}"
    dir_count=$(ls | wc -l)
    if [ "$dir_count" -gt 10 ]; then
        rm -f $(ls -tr | head -1)
    fi
done

Script 5: Extract today’s GC logs and compute average and maximum GC times

The script parses hive-server2.log (assumed to be the GC log), extracts the second column (the GC time), removes colons, then calculates the average and the maximum GC duration, appending the results to capture_hive_log.log.

#!/bin/bash
awk '{print $2}' hive-server2.log | tr -d ':' | awk '{sum+=$1} END {print "avg: ", sum/NR}' >>capture_hive_log.log
awk '{print $2}' hive-server2.log | tr -d ':' | awk '{max=0} {if ($1+0 > max+0) max=$1} END {print "Max: ", max}' >>capture_hive_log.log

Script 6: Monitor top 20 IPs on port 80 and trigger alert when requests exceed 500

The script repeatedly checks the number of connections on port 80, finds the smallest request count among the top‑20 IPs, and if that count is greater than 500 it records a system activity report to alert.txt; otherwise it sleeps for six seconds and retries.

#!/bin/bash
state="true"
while $state; do
    SMALL_REQUESTS=$(netstat -ant | awk -F'[ :]' '/:22/{count[$4]++} END {for(ip in count) print count[ip]}' | sort -n | head -20 | head -1)
    if [ "$SMALL_REQUESTS" -gt 500 ]; then
        sar -A > alert.txt
        state="false"
    else
        sleep 6
        continue
    fi
done

Script 7: Move files larger than 10 KB to /tmp and list them by size

The script moves every file larger than 10 KB from the current directory to /tmp, then lists the files in /tmp sorted from largest to smallest.

#!/bin/bash
DIRPATH='/tmp'
FILEPATH='.'
find "$FILEPATH" -size +10k -type f | xargs -I {} mv {} "$DIRPATH"
ls -lS "$DIRPATH" | awk '{if(NR>1) print $NF}'

These seven examples provide ready‑to‑run Bash snippets that illustrate common sysadmin tasks such as parallel remote execution, process monitoring, file manipulation, log analysis, and automated alerting.

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.

AutomationSysadminlog analysisShell scriptingprocess monitoring
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

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.