這部分主要討論數學相關的shell腳本編程。
加法運算
新建一個文件“Addition.sh”,輸入下面的內容并賦予其可執行的權限。
復制代碼 代碼如下:#!/bin/bash
echo “Enter the First Number: ”
read a
echo “Enter the Second Number: ”
read b
x=$(expr "$a" + "$b")
echo $a + $b = $x
輸出結果:
復制代碼 代碼如下:
[root@tecmint ~]# vi Additions.sh
[root@tecmint ~]# chmod 755 Additions.sh
[root@tecmint ~]# ./Additions.sh
“Enter the First Number: ”
12
“Enter the Second Number: ”
13
12 + 13 = 25
減法運算
復制代碼 代碼如下:
#!/bin/bash
echo “Enter the First Number: ”
read a
echo “Enter the Second Number: ”
read b
x=$(($a - $b))
echo $a - $b = $x
注意:這里我們沒有像上面的例子中使用“expr”來執行數學運算。
輸出結果:
復制代碼 代碼如下:
[root@tecmint ~]# vi Substraction.sh
[root@tecmint ~]# chmod 755 Substraction.sh
[root@tecmint ~]# ./Substraction.sh
“Enter the First Number: ”
13
“Enter the Second Number: ”
20
13 - 20 = -7
乘法運算
復制代碼 代碼如下:
#!/bin/bash
echo “Enter the First Number: ”
read a
echo “Enter the Second Number: ”
read b
echo "$a * $b = $(expr $a /* $b)"
輸出結果:
復制代碼 代碼如下:
[root@tecmint ~]# vi Multiplication.sh
[root@tecmint ~]# chmod 755 Multiplication.sh
[root@tecmint ~]# ./Multiplication.sh
“Enter the First Number: ”
11
“Enter the Second Number: ”
11
11 * 11 = 12
除法運算
復制代碼 代碼如下:
#!/bin/bash
echo “Enter the First Number: ”
read a
echo “Enter the Second Number: ”
read b
echo "$a / $b = $(expr $a / $b)"
輸出結果:
復制代碼 代碼如下:
[root@tecmint ~]# vi Division.sh
[root@tecmint ~]# chmod 755 Division.sh
[root@tecmint ~]# ./Division.sh
“Enter the First Number: ”
12
“Enter the Second Number: ”
3
12 / 3 = 4
數組
下面的這個腳本可以打印一組數字。
復制代碼 代碼如下:
#!/bin/bash
echo “Enter The Number upto which you want to Print Table: ”
read n
i=1
while [ $i -ne 10 ]
do
i=$(expr $i + 1)
table=$(expr $i /* $n)
echo $table
done
輸出結果:
復制代碼 代碼如下:
[root@tecmint ~]# vi Table.sh
[root@tecmint ~]# chmod 755 Table.sh
[root@tecmint ~]# ./Table.sh
“Enter The Number upto which you want to Print Table: ”
29
58
87
116
145
174
203
232
261
290
你可以從這里下載這個例子的代碼
判斷奇偶數
新聞熱點
疑難解答