0

抱歉信息的位和片段所以我正在编写一个普通的shell脚本程序,所以如果使用输入

echo 1 3, .... | sh get_number

我必须将由空格分隔的数字从 echo 中提取出来

var1 = 1,var2= 3,等等。

我试过了

#!/bin/sh
sum=0 
for i in $* 
do 
sum=`expr $sum + $i` 
done 
avg=`expr $sum / $n`
echo Average=$avg 

但不起作用....我是否在此处包含阅读内容?另外,我将如何 sh get_number <file1>, <file2>...获取其中的数字并将它们与 shell 脚本相加?

谢谢

4

3 回答 3

1

要修复您的代码:

for i in $*; do
    sum=$(( sum + i ))
    n=$(( n + 1 ))
done
echo "Average=$(( sum / n ))"
于 2013-10-11T16:58:12.443 回答
1

听起来您正在寻找read内置的 shell:

% echo "1 2 3 4" | read a b stuff
% echo $b
2
% echo $stuff
3 4

于 2013-10-11T15:39:29.930 回答
0
#!/bin/sh

while [ $# -gt 0 ]; do
    (( i++ ))
    (( sum += $1 ))
    shift
done
echo "Average=$(( sum/i ))"

Note: This fails in dash which is the closest shell I could find to a real sh.

An example of reading values from files passed as command line arguments or from lines read from stdin:

add_to_sum() {
    set $*
    while [ $# -gt 0 ]; do
        I=`expr $I + 1`
        SUM=`expr $SUM + $1`
        shift
    done
}

I=0
SUM=0

if [ $# -gt 0 ]; then
    # process any arguments on the command line
    while [ $# -gt 0 ]; do
        FILE=$1
        shift
        while read LINE; do 
            add_to_sum "$LINE"
        done < "$FILE"
    done
else
    # if no arguments on the command line, read from stdin
    while read LINE; do
        add_to_sum "$LINE"
    done
fi

# be sure not to divide by zero
[ $I -gt 0 ] && echo Average=`expr $SUM / $I`
于 2013-10-11T16:54:02.107 回答