急~關於Linux&&shell script

2010-05-22 4:50 pm
我的原問題是→讓使用者輸入一個數字,程式可以由 1+2+3... 一直累加到使用者輸入的數字為止。

程式如下:

#!/bin/bash
read -p "Please input an integer number: " number
i=0
s=0
while [ "$i" != "$number" ]
do
i=$(($i+1))
s=$(($s+$i))
done
echo "the result of '1+2+3+...$number' is ==> $s"

之後老師要我改寫成→允許使用者準備一個輸入檔,當某列有1個數字,則使用原邏輯,若有2個數字則為起始與結束數字。

意思就是 當我們輸入1個數字10 程式會從1+到10
當我們輸入2個數字3 10 程式會從3+到10

如果以我的程式改寫,請問要怎麼改寫啊???
更新1:

感謝您的回答 基於我才剛學Linux 我有些地方看的不是很懂 可以請你稍微解釋一下嘛 比如 #!/home/dag/bin/bin/bash 為什麼要加/home/dag跟兩個bin x=${line%% *} y=${line##* } 這個大括號 跟裡面的%跟*跟#的用途 while [ "$i" -le "$number" ] 這一行 -le是什麼用途的 還有這一行意思是?? 大概是這樣子了,先感謝你的回答~~~~~^^

回答 (1)

2010-05-24 1:55 pm
✔ 最佳答案
#!/home/dag/bin/bin/bash

read -p "Please input one or two integer number(s):" line

x=${line%% *}
y=${line##* }
let i=$x+0
let number=$y+0

if [[ $i == $number ]]
then
i=1
x=1
fi

s=0
while [ "$i" -le "$number" ]
do
s=$(($s+$i))
i=$(($i+1))
done

echo "the result of '$x+...$number' is ==> $s"


2010-05-25 01:04:51 補充:
Sorry about the confusion.
1. #!/bin/bash is your path to your bash shell. Mine is an experimental build. I built it for debugging. You should use your own.
2.You can ignore my bash shell path and should use your own.

2010-05-25 01:09:18 補充:
3. ## and %% are variable, parameter expansion/substitution. Basically, these are pattern matching symbols. You can check out the following website for more (there are a lot more than these 2).
http://tldp.org/LDP/abs/html/parameter-substitution.html
4. le is "less than"

2010-05-25 01:19:52 補充:
4. le is "less than or equal to". For example, exp1 -le exp2 is true if exp1 is less than or equal to the value of exp2


收錄日期: 2021-04-30 12:53:56
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20100522000016KK01583

檢視 Wayback Machine 備份