萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Shell 腳本實戰精選:8 個常用自動化範例(判斷輸入、求平均、批量測試、備份等)

Shell 腳本是 Linux 運維自動化的基石。本文精選 8 個實用片段,涵蓋互動判斷、數值計算、參數處理、檔案批量操作、磁碟壓力測試、配置讀取、正則驗證、日期備份,可直接套用或修改擴充。

範例 1:判斷輸入為數字、字母或其他

#!/bin/bash
read -p "Enter a number or string: " input
case $input in
    [0-9]) echo "Good job, numeric!" ;;
    [a-zA-Z]) echo "Good job, character!" ;;
    *) echo "Wrong input, try again!" ;;
esac

範例 2:互動式計算平均分

#!/bin/bash
SCORE=0; SUM=0; NUM=0; AVERAGE=0
while true; do
    read -p "Enter score [0-100%] (q to quit): " SCORE
    if [[ $SCORE == "q" ]]; then
        echo "Average: $AVERAGE%"; break
    elif (( SCORE < 0 || SCORE > 100 )); then
        echo "Be serious, try again."
    else
        SUM=$((SUM + SCORE))
        NUM=$((NUM + 1))
        AVERAGE=$((SUM / NUM))
    fi
done

範例 3:遞減輸出參數列表

#!/bin/bash  # doit.sh
while (( $# > 0 )); do
    echo $*
    shift
done
$ ./doit.sh a b c d e
a b c d e
b c d e
c d e
d e
e

範例 4:讀取檔案每行加前綴

#!/bin/bash
for name in $(cat namelist); do
    echo "name= $name"
done
echo "The name is out of namelist file"

範例 5:批量測試檔案是否存在

#!/bin/bash
for file in test*.sh; do
    if [ -f "$file" ]; then
        echo "$file existed."
    fi
done

範例 6:指定大小檔案填滿磁碟(壓力測試)

#!/bin/bash
counter=0; max=3800
while true; do
    ((counter++))
    (( ${#counter} > max )) && break
    (( counter % 1000 == 0 )) && echo "counter=$counter date=$(date)"
    mkdir -p /tmp/temp
    cat testfile > "/tmp/temp/myfile.$counter" || { echo "Disk full"; exit 1; }
done
echo "Done!"
# 建立 1MB 測試檔:dd if=/dev/zero of=testfile bs=1M count=1

範例 7:逐行讀取配置檔到陣列

#!/bin/bash
i=0
while read LINE; do
    hosts_allow[i]=$LINE
    ((i++))
done < hosts.allow
for ((i=0; i<${#hosts_allow[@]}; i++)); do
    echo ${hosts_allow[i]}
done

範例 8:簡單正則驗證與日期備份

#!/bin/bash
# 驗證 6 位英數字
regex="[A-Za-z0-9]{6}"
[[ $1 =~ $regex ]] && echo $1 || { echo "Invalid"; exit 1; }

# 日期備份
NOW=$(date +"%m-%d-%Y")
tar zcvf "/tmp/backup.$NOW.tar.gz" /home /etc /var
copyright © 萬盛學電腦網 all rights reserved