Shell指令碼 程式設計高階08

2021-10-06 18:22:50 字數 2565 閱讀 8591

1、編寫函式實現兩個數字做為引數,返回最大值

maxnum(

)

#!/bin/bash

. functions

read -p "please input first digits :" num1

read -p "please input second digits :" num2

max=

$(maxnum $num1 $num2)if[

[!$max

=~ ^[

[:digit:]

]+$ ]

]then

echo

$max

continue

else

echo

"最大的數是$max"

fi

[root@centos7 ~]

# ./max.sh

please input first digits :100

please input second digits :200

最大的數是200

2、斐波那契數列又稱**分割數列,因數學家列昂納多·斐波那契以兔子繁殖為例子而引入,故又稱為「兔子數列」,指的是這樣乙個數列:0、1、1、2、3、5、8、13、21、34、……,斐波納契數列以如下被以遞迴的方法定義:f(0)=0, f(1)=1,f(n)=f(n-1)+f(n-2)(n≥2),利用函式,求 n 階斐波那契數列;
fibonacci(

)

#!/bin/bash

. functions

while:do

echo

> f1.tmp

read -p "請輸入斐波拉契數列的階數(大於等於2的整數,輸入 q 退出):" n

if[$n

=="q"

]then

break

elif[[

!$n=~ ^[

[:digit:]

]+$ ]

]then

echo

"您輸入的不是正整數,請重新輸入。"

continue

elif

[$n -lt 2 ]

then

echo

"您輸入的數字小於2,請重新輸入。"

continue

else

for i in

`seq $n`

doecho -e "$i:\c"

fibonacci $[i-1]

done

fidone

[root@centos7 ~]

# ./fibonacci.sh

請輸入斐波拉契數列的階數(大於等於2的整數,輸入 q 退出):5

1:02:1

3:14:2

5:3請輸入斐波拉契數列的階數(大於等於2的整數,輸入 q 退出):10

1:02:1

3:14:2

5:36:5

7:88:13

9:21

10:34

請輸入斐波拉契數列的階數(大於等於2的整數,輸入 q 退出):q

3、漢諾塔(又稱河內塔)問題是源於印度乙個古老傳說。大梵天創造世界的時候做了三根金剛石柱子,在一根柱子上從下往上按照大小順序摞著64片**圓盤。大梵天命令婆羅門把圓盤從下面開始按大小順序重新擺放在另一根柱子上。並且規定,在小圓盤上不能放大圓盤,在三根柱子之間一次只能移動乙個圓盤,利用函式,實現n片盤的漢諾塔的移動步驟
#!/bin/bash

function hanoi(

)# 5個盤,修改下一行的數字,指定盤子數量

hanoi 5 'a'

'b''c'

[root@centos7 ~]

# ./hannota.sh

move a to c

move a to b

move c to b

move a to c

move b to a

move b to c

move a to c

move a to b

move c to b

move c to a

move b to a

move c to b

move a to c

move a to b

move c to b

move a to c

move b to a

move b to c

move a to c

move b to a

move c to b

move c to a

move b to a

move b to c

move a to c

move a to b

move c to b

move a to c

move b to a

move b to c

move a to c

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

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

Shell指令碼 程式設計高階03

1 每隔 3 秒鐘到系統上獲取已經登入的使用者的資訊 如果發現使用者 hacker 登入,則將登入時間和主機記錄於日誌 var log login.log 中,並退出指令碼 bin bash while do echo date f t no information if who grep hack...

7 Shell指令碼程式設計高階

1 編寫指令碼實現傳入程序pid,檢視對應程序 proc下的cpu 記憶體指標。bin bash color red start 1 31m color red end 0m read p please input the pid to check cpu mem infomation pid ch...