Shell 腳本是 Linux 運維自動化的基石。本文精選 8 個實用片段,涵蓋互動判斷、數值計算、參數處理、檔案批量操作、磁碟壓力測試、配置讀取、正則驗證、日期備份,可直接套用或修改擴充。
#!/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
#!/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
#!/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
#!/bin/bash
for name in $(cat namelist); do
echo "name= $name"
done
echo "The name is out of namelist file"
#!/bin/bash
for file in test*.sh; do
if [ -f "$file" ]; then
echo "$file existed."
fi
done
#!/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
#!/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
#!/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