shell學習:幾道常見shell習題

來源:互聯網
上載者:User

標籤:

1. 編寫shell指令碼,計算1-100的和;

2. 編寫shell指令碼,要求輸入一個數字,然後計算出從1到輸入數位和,要求,如果輸入的數字小於1,則重新輸入,直到輸入正確的數字為止;

3. 編寫shell指令碼,把/root/目錄下的所有目錄(只需要一級)拷貝到/tmp/目錄下;

4. 編寫shell指令碼,批量建立使用者user_00, user_01, … ,user_100並且所有使用者同屬於users組;

5. 編寫shell指令碼,截取檔案test.log中包含關鍵詞’abc’的行中的第一列(假設分隔字元為”:”),然後把截取的數字排序(假設第一列為數字),然後列印出重複次數超過10次的列;

6. 編寫shell指令碼,判斷輸入的IP是否正確(IP的規則是,n1.n2.n3.n4,其中1<n1<255, 0<n2<255, 0<n3<255, 0<n4<255)。

以下為練習題答案:

1. #! /bin/bash

sum=0

for i in `seq 1 100`; do

sum=$[$i+$sum]

done

echo $sum

2. #! /bin/bash

n=0

while [ $n -lt "1" ]; do

read -p "Please input a number, it must greater than "1":" n

done

 

sum=0

for i in `seq 1 $n`; do

sum=$[$i+$sum]

done

echo $sum

 

3. #! /bin/bash

for f in `ls /root/`; do

if [ -d $f ] ; then

cp -r $f /tmp/

fi

done

 

4. #! /bin/bash

groupadd users

for i in `seq 0 9`; do

useradd -g users user_0$i

done

 

for j in `seq 10 100`; do

useradd -g users user_$j

done

 

5. #! /bin/bash

awk -F‘:‘ ‘$0~/abc/ {print $1}‘ test.log >/tmp/n.txt

sort -n n.txt |uniq -c |sort -n >/tmp/n2.txt

awk ‘$1>10 {print $2}‘ /tmp/n2.txt

 

6. #! /bin/bash

checkip() {

if echo $1 |egrep -q ‘^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$‘ ; then

a=`echo $1 | awk -F. ‘{print $1}‘`

b=`echo $1 | awk -F. ‘{print $2}‘`

c=`echo $1 | awk -F. ‘{print $3}‘`

d=`echo $1 | awk -F. ‘{print $4}‘`

 

for n in $a $b $c $d; do

if [ $n -ge 255 ] || [ $n -le 0 ]; then

echo "the number of the IP should less than 255 and greate than 0"

return 2

fi

done

else

echo "The IP you input is something wrong, the format is like 192.168.100.1"

return 1

fi

}

 

rs=1

while [ $rs -gt 0 ]; do

read -p "Please input the ip:" ip

checkip $ip

rs=`echo $?`

done

echo "The IP is right!"

shell學習:幾道常見shell習題

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.