在這裏你去(假設bash
,不sh
):
#!/bin/bash
sum=0
if (($# == 0)); then
# Read line by line
# But each line might consist of separate numbers to be added
# So read each line as an array!
while read -a data; do
# Now data is an array... but if empty, continue
((${#data[@]})) || continue
# Convert this array into a string s, with elements separated by a +
printf -v s "%s+" ${data[@]}
# Append 0 to s (observe that s ended with a +)
s="${s}0"
# Add these numbers to sum
((sum += s))
done
else
# If elements come from argument line, do the same!
printf -v s "%s+" [email protected]
# Append 0 to s (observe that s ended with a +)
s="${s}0"
# Add these numbers to obtain sum
((sum = s))
fi
echo $sum
你可以這樣調用它:
$ echo 10 12 13 | ./sum
35
$ ./sum 10 12 13
35
$ # With several lines and possibly empty lines:
$ { echo 10 12 13; echo; echo 42 22; } | ./sum
99
希望這會有所幫助!
編輯。您可能也有興趣學習關於IFS
的酷東西。我注意到人們往往會在bash
中混淆@
和*
。如果你不知道我在說什麼,那麼你應該使用@
而不是*
,也可以用於數組下標!在bash
手冊中,您會發現當雙引號時,$*
(或${array[*]}
)展開爲由IFS
的值分隔的數組的所有元素。這在我們的情況下可能很有用:
#!/bin/bash
sum=0
if (($# == 0)); then
# Read line by line
# But each line might consist of separate numbers to be added
# So read each line as an array!
while read -a data; do
# Now data is an array... but if empty, continue
((${#data[@]})) || continue
# Setting IFS=+ (just for the sum) will yield exactly what I want!
IFS=+ sum=$((sum + ${data[*]}))
done
else
# If elements come from argument line, do the same!
# Setting IFS=+ (just for the sum) will yield exactly what I want!
IFS=+ sum=$(($*))
fi
echo $sum
Gniourf現在退出教師模式。 :-)
你正在使用'bash',對吧?因爲你的for循環不是'sh'循環。 –
對不起,我是初學者。我真的不明白 –
好吧,讓我們假設你正在使用'bash'。它不起作用,因爲在第二種情況下,變量'data'包含'10 12 13' ... –