Shell指令碼 程式設計高階03

2021-10-06 18:22:50 字數 2163 閱讀 8494

1、每隔 3 秒鐘到系統上獲取已經登入的使用者的資訊;如果發現使用者 hacker 登入,則將登入時間和主機記錄於日誌 /var/log/login.log 中,並退出指令碼;

#!/bin/bash

while:do

echo

"<----`

date +'%f %t'

`----no information !---->"if[

[`who|

grep hacker` ]]

then

echo user hacker was logined in

`date +'%f %t'` |

tee /var/log/login.log

break

fisleep 3

done

[root@centos7 ~]

# ./login.sh

<----2020-06-02 10:36:55----no information !---->

user hacker was logined in 2020-06-02 10:36:55

[root@centos7 ~]

# cat /var/log/login.log

user hacker was logined in 2020-06-02 10:36:55

2、隨機生成 10 以內的數字,實現猜字遊戲,提示比較大或小,相等則退出;
#!/bin/bash

num=$[

$random%10]

while:do

read -p "please guess:" n

if[$n -lt $num

]then

echo

"to little ! again."

elif

[$n -gt $num

]then

echo

"to large ! again."

else

echo

"congritulation !!!"

break

fidone

[root@centos7 ~]

# ./guess.sh

please guess:5

to little ! again.

please guess:8

to little ! again.

please guess:9

congritulation !

!!

3、用檔名做為引數,統計所有引數檔案的總行數;
#!/bin/bash

sum=0

while[$1

]doi=`

cat $1 |

wc -l`

let sum+=i

shift

done

echo

$sum

[root@centos7 ~]

# ./file_count.sh /etc/fstab /etc/resolv.conf /etc/chrony.conf

50

4、用二個以上的數字為引數,顯示其中的最大值和最小值。
#!/bin/bash

max=

$1min=$1[

[ $# -lt 2 ]] && echo 指定的引數太少。 && exit

while[$1

]do[$1 -gt $max]&&

let max=$1[

$1 -lt $min]&&

let min=

$1shift

done

echo max:$max,min:$min

[root@centos7 ~]

# ./maxmin.sh

指定的引數太少。

[root@centos7 ~]

# ./maxmin.sh 10

指定的引數太少。

[root@centos7 ~]

# ./maxmin.sh 10 100 1000

max:1000,min:10

shell指令碼程式設計高階(一)

可以巢狀 分支if 判斷條件 then 條件為真的分支 fiif 判斷條件 then 條件為真的分支 else 條件為假的分支 fiif 判斷條件1 then 條件1為真的分支 elif 判斷條件2 then 條件2為真的分支 elif 判斷條件3 then 條件3為真的分支 else 以上條件都為...

Shell指令碼 程式設計高階08

1 編寫函式實現兩個數字做為引數,返回最大值maxnum bin bash functions read p please input first digits num1 read p please input second digits num2 max maxnum num1 num2 if m...

shell指令碼程式設計 sed 03

shell指令碼程式設計 sed 03 指令 p 輸出 d 刪除 1.刪除檔案最後一行 sed d test.txt 2.刪除檔案的空行 sed d test.txt s 替換 語法結構 1.sed s old new test.txt 替換第乙個匹配到的old 2.sed s old new g ...