1. 程式人生 > 其它 >幾個簡單有趣的shell指令碼

幾個簡單有趣的shell指令碼

技術標籤:Linux

文章目錄

1.猜數字

#!/bin/bash
 
 
# 指令碼生成一個 100 以內的隨機數,提示使用者猜數字,根據使用者的輸入,提示使用者猜對了,
# 猜小了或猜大了,直至使用者猜對指令碼結束。
 
# RANDOM 為系統自帶的系統變數,值為 0‐32767的隨機數
# 使用取餘演算法將隨機數變為 1‐100 的隨機數
num=$[RANDOM%100+1]
echo "$num"
 
# 使用 read 提示使用者猜數字
# 使用 if 判斷使用者猜數字的大小關係:‐eq(等於),‐ne(不等於),‐gt(大於),‐ge(大於等於),
# ‐lt(小於),‐le(小於等於) 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

2.石頭剪刀布

#!/bin/bash
 
game=(石頭 剪刀 布)
num=$[RANDOM%3]
computer=${game[$num]}
 
 
echo "請根據下列提示選擇您的出拳手勢"
echo " 1. 石頭"
echo " 2. 剪刀"
echo " 3. 布 "
 
read -p "請選擇 1-3 :" person
echo "      $(($person)) VS $((num+1))" 
echo "你:${game[$person-1]} VS 電腦:$computer
"
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

3.排大小

#!/bin/bash
 
# 依次提示使用者輸入 3 個整數,指令碼根據數字大小依次排序輸出 3 個數字
read -p " 請輸入一個整數: " num1
read -p " 請輸入一個整數: " num2
read -p " 請輸入一個整數:  " num3
 
# 不管誰大誰小,最後都列印 echo "$num1,$num2,$num3"
# num1 中永遠存最小的值,num2 中永遠存中間值,num3 永遠存最大值
# 如果輸入的不是這樣的順序,則改變數的儲存順序,如:可以將 num1 和 num2 的值對調
tmp=0
# 如果 num1 大於 num2,就把 num1 和和 num2 的值對調,確保 num1 變數中存的是最小值
if [ $num1 -gt $num2 ];then
	tmp=$num1
	num1=$num2
	num2=tmp
fi
# 如果 num1 大於 num3,就把 num1 和 num3 對調,確保 num1 變數中存的是最小值
if [ $num1 -gt $num3 ];then
	tmp=$num1
	num1=$num3
	num3=$tmp
fi
# 如果 num2 大於 num3,就把 num2 和 num3 對調,確保 num2 變數中存的是最小值
if [ $num2 -gt $num3 ];then
	tmp=$num2
	num2=$num3
	num3=$tmp
fi
echo "排序後資料(從小到大)為:$num1,$num2,$num3"

4.時鐘

#!/bin/bash

# 使用死迴圈實時顯示 eth0 網絡卡傳送的資料包流量 

while :
do
        echo "當前時間是:$(date +"%Y‐%m‐%d %H:%M:%S")"
        sleep 1
done

5.開機啟動問候

tips:將該指令碼放到 /etc/profile.d/ 路徑下用於開機問候

#!/bin/bash
# 根據計算機當前時間,返回問候語,可以將該指令碼設定為開機啟動 
 
# 00‐12 點為早晨,12‐18 點為下午,18‐24 點為晚上
# 使用 date 命令獲取時間後,if 判斷時間的區間,確定問候語內容
json=`curl -s http://www.weather.com.cn/data/sk/101010100.html`
#echo $json
city=`echo $json | sed 's/.*city":"//g'| sed 's/","cityid.*$//g'`
temp=`echo $json | sed 's/.*temp":"//g'| sed 's/","WD.*$//g'`
wd=`echo $json | sed 's/.*WD":"//g'| sed 's/","WS.*$//g'`
ws=`echo $json | sed 's/.*WS":"//g'| sed 's/","SD.*$//g'`
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"
echo 'you are now at '$city','$temp'℃,'$ws$wd'.'

6.列印國際象棋

#!/bin/bash
# 列印國際象棋棋盤
# 設定兩個變數,i 和 j,一個代表行,一個代表列,國際象棋為 8*8 棋盤
# i=1 是代表準備列印第一行棋盤,第 1 行棋盤有灰色和藍色間隔輸出,總共為 8 列
# i=1,j=1 代表第 1 行的第 1 列;i=2,j=3 代表第 2 行的第 3 列
# 棋盤的規律是 i+j 如果是偶數,就列印藍色色塊,如果是奇數就列印灰色色塊
# 使用 echo ‐ne 列印色塊,並且列印完成色塊後不自動換行,在同一行繼續輸出其他色塊
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

在這裡插入圖片描述

7. 列印乘法表

#!/bin/bash
 for i in `seq 9`
 do 
     for j in `seq $i`
     do
         echo -n "$i*$j=$[i*j] "
     done
     echo
 done

在這裡插入圖片描述

8. 彩色動態管道

#!/bin/bash
# The author of the original script is unknown to me. The first entry I can
# find was posted at 2010-03-21 09:50:09 on Arch Linux Forums (doesn't mean the
# poster is the author at all):
#
#   Post your handy self made command line utilities (Page 37) / Programming & Scripting / Arch Linux Forums
#
# I, Yu-Jie Lin, made a few changes and additions:
#
#   -p, -t, -R, and -C
#
#   Screenshot: http://flic.kr/p/dRnLVj
#   Screencast: http://youtu.be/5XnGSFg_gTk
#
# And push the commits to Gist:
#
#   https://gist.github.com/4689307
#
# I, Devin Samarin, made a few changes and additions:
#
#   -r can be 0 to mean "no limit".
#   Reset cursor visibility after done.
#   Cleanup for those people who want to quit with ^C
#
#   Pushed the changes to https://gist.github.com/4725048
#   hole1: https://gist.githubusercontent.com/livibetter/4689307/raw/949e43fe2962c2c97c8b1d974ff93dd053d9bd37/pipes.sh
#   hole2: Fun On The Terminal Part 2

p=1
f=75 s=13 r=2000 t=0
w=$(tput cols) h=$(tput lines)
# ab -> idx = a*4 + b
# 0: up, 1: right, 2: down, 3: left
# 00 means going up   , then going up   -> ┃
# 12 means going right, then going down -> ┓
sets=(
    "┃┏ ┓┛━┓  ┗┃┛┗ ┏━"
    "│╭ ╮╯─╮  ╰│╯╰ ╭─"
    "│┌ ┐┘─┐  └│┘└ ┌─"
    "║╔ ╗╝═╗  ╚║╝╚ ╔═"
)
v="${sets[0]}"
RNDSTART=0
NOCOLOR=0

OPTIND=1
while getopts "p:t:f:s:r:RCh" arg; do
case $arg in
    p) ((p=(OPTARG>0)?OPTARG:p));;
    t) ((OPTARG>=0 && OPTARG<${#sets[@]})) && v="${sets[OPTARG]}";;
    f) ((f=(OPTARG>19 && OPTARG<101)?OPTARG:f));;
    s) ((s=(OPTARG>4 && OPTARG<16 )?OPTARG:s));;
    r) ((r=(OPTARG>=0)?OPTARG:r));;
    R) RNDSTART=1;;
    C) NOCOLOR=1;;
    h) echo -e "Usage: $(basename $0) [OPTION]..."
        echo -e "Animated pipes terminal screensaver.\n"
        echo -e " -p [1-]\tnumber of pipes (D=1)."
        echo -e " -t [0-$((${#sets[@]} - 1))]\ttype of pipes (D=0)."
        echo -e " -f [20-100]\tframerate (D=75)."
        echo -e " -s [5-15]\tprobability of a straight fitting (D=13)."
        echo -e " -r LIMIT\treset after x characters, 0 if no limit (D=2000)."
        echo -e " -R \t\trandom starting point."
        echo -e " -C \t\tno color."
        echo -e " -h\t\thelp (this screen).\n"
        exit 0;;
    esac
done

cleanup() {
    tput rmcup
    tput cnorm
    exit 0
}
trap cleanup SIGHUP SIGINT SIGTERM

for (( i=1; i<=p; i++ )); do
    c[i]=$((i%8)) n[i]=0 l[i]=0
    ((x[i]=RNDSTART==1?RANDOM*w/32768:w/2))
    ((y[i]=RNDSTART==1?RANDOM*h/32768:h/2))
done

tput smcup
tput reset
tput civis
while ! read -t0.0$((1000/f)) -n1; do
    for (( i=1; i<=p; i++ )); do
        # New position:
        ((${l[i]}%2)) && ((x[i]+=-${l[i]}+2,1)) || ((y[i]+=${l[i]}-1))

        # Loop on edges (change color on loop):
        ((${x[i]}>w||${x[i]}<0||${y[i]}>h||${y[i]}<0)) && ((c[i]=RANDOM%8))
        ((x[i]=(x[i]+w)%w))
        ((y[i]=(y[i]+h)%h))

        # New random direction:
        ((n[i]=RANDOM%s-1))
        ((n[i]=(${n[i]}>1||${n[i]}==0)?${l[i]}:${l[i]}+${n[i]}))
        ((n[i]=(${n[i]}<0)?3:${n[i]}%4))

        # Print:
        tput cup ${y[i]} ${x[i]}
        [[ $NOCOLOR == 0 ]] && echo -ne "\033[1;3${c[i]}m"
        echo -n "${v:l[i]*4+n[i]:1}"
        l[i]=${n[i]}
    done
    ((r>0 && t*p>=r)) && tput reset && tput civis && t=0 || ((t++))
done
cleanup

在這裡插入圖片描述


參考:https://blog.csdn.net/weixin_42405670/article/details/89818462