1. 程式人生 > >shell實戰訓練營Day18

shell實戰訓練營Day18

提示使用者輸入網絡卡的名字,然後我們用指令碼輸出網絡卡的ip,需要考慮下面問題:

輸入的字元不符合網絡卡名字規範,怎麼應對。
名字符合規範,但是根本就沒有這個網絡卡又怎麼應對。
#!/bin/bash
ip add |awk -F ': ' '$1 ~ "^[1-9]" {print $2}' > /tmp/eth.list
while :
do
eths=cat /tmp/eth.list |xargs
read -p "Please input a if name(The eths is echo -e "\033[31m$eths\033[0m"): " eth
if [ -z "$eth" ]
then
echo "Please input a if name."
continue
fi
if ! grep -qw "$eth" /tmp/eth.list
then
echo "The if name is error."
continue
else
break
fi
done

if_ip()
{
ip add show dev $1 |grep ' inet ' |awk '{print $2}'|awk -F '/' '{print $1}' >/tmp/$1.txt
n=wc -l /tmp/$1.txt|awk '{print $1}'
if [ $n -eq 0 ]
then
echo "There is no ip address on the eth."
else
echo "The ip addreess is:"
for ip in cat /tmp/$1.txt
do
echo -e "\033[33m$ip\033[0m"
done
fi
}

if_ip $eth

寫一個指令碼,實現如下功能:

指令碼可以帶引數也可以不帶
引數可以有多個,每個引數必須是一個目錄
指令碼檢查引數個數,若等於0,則列出當前目錄本身,否則顯示每個引數包含的子目錄。

#!/bin/bash
if [ $# -eq 0 ]
then
echo "當前目錄下的檔案是:"
ls .
else
for d in [email protected]
do
if [ -d $d ]
then
echo "目錄$d下有這些子目錄:"
find $d -type d
else
echo "並沒有該目錄:$d"
fi
done
fi

定義一個shell函式,能接受兩個引數,滿足以下要求:

第一個引數為URL,即可下載的檔案,第二個引數為目錄,即下載後儲存的位置
如果使用者給的目錄不存在,則提示使用者是否建立,如果建立就繼續執行,否則,函式返回一個51的錯誤值給呼叫指令碼
如果給的目錄存在,則下載檔案,下載命令執行結束後測試檔案下載成功與否,如果成功,則返回0給呼叫指令碼,否則,返回52給呼叫指令碼

#!/bin/bash
if [ $# -ne 2 ]
then
echo "你必須要輸入兩個引數,第一個引數是網址,第二個引數是目錄."
exit 1
fi

if [ ! -d $2 ]
then
while :
do
echo "你輸入的第二個引數,並不是一個存在的目錄。是否要建立該目錄呢?(y|n): "c
case $c in
y|Y)
mkdir -p $2
;;
n|N)
exit 51
;;
*)
echo "請輸入y或者n."
continue
;;
esac
done
else
cd $2
wget $1
if [ $? -eq 0 ]
then
exit 0
else
echo "下載失敗."
exit 52
fi
fi

寫一個猜數字指令碼,當用戶輸入的數字和預設數字(隨機生成一個0-100的數字)一樣時,直接退出,否則讓使用者一直輸入,並且提示使用者的數字比預設數字大或者小。

#!/bin/bash
n=$[$RANDOM%101]
while :
do
read -p "請輸入一個0-100的數字:" n1
if [ -z "$n1" ]
then
echo "必須要輸入一個數字。"
continue
fi
n2=echo $n1 |sed 's/[0-9]//g'
if [ -n "$n2" ]
then
echo "你輸入的數字並不是正整數."
continue
else
if [ $n -gt $n1 ]
then
echo "你輸入的數字小了,請重試。"
continue
elif [ $n -lt $n1 ]
then
echo "你輸入的數字大了,請重試。"
continue
else
echo "恭喜你,猜對了!"
break
fi
fi
done

寫一個shell指令碼,能實現如下需求:

執行指令碼後,提示輸入名字(英文的,可以是大小寫字母、數字不能有其他特殊符號),然後輸出一個隨機的0-99之間的數字,指令碼並不會退出,繼續提示讓輸入名字
如果輸入相同的名字,輸出的數字還是第一次輸入該名字時輸出的結果
前面已經輸出過的數字,下次不能再出現
當輸入q或者Q時,指令碼會退出。

#!/bin/bash
f=/tmp/user_number.txt
j_n()
{
while :
do
n=$[RANDOM%100]
if awk '{print $2}' $f|grep -qw $n
then
continue
else
break
fi
done
}

while :
do
read -p "Please input a username: " u
if [ -z "$u" ]
then
echo "請輸入使用者名稱."
continue
fi

if [ $u == "q" ] || [ $u == "Q" ]
then
exit
fi 

u1=`echo $u|sed 's/[a-zA-Z0-9]//g'`
if [ -n "$u1" ]
then
echo "你輸入的使用者名稱不符合規範,正確的使用者名稱應該是大小寫字母和數字的組合"
continue
else
if [ -f $f ]
then
    u_n=`awk -v uu=$u '$1==uu {print $2}' $f`
    if [ -n "$u_n" ]
    then
    echo "使用者$u對應的數字是:$u_n"
    else
    j_n
    echo "使用者$u對應的數字是:$n"
        echo "$u $n" >>$f
    fi
else
    j_n
    echo "使用者$u對應的數字是:$n"
    echo $u $n >> $f
fi
fi

done