1

这是我的代码:我想在临时目录中创建一个临时变量。我创建了一个名为 read-series 的函数,它读取整数直到 ctrl-d,然后将它们附加到 .tmp。然后它传递给偶数奇数,它对偶数和赔率之和的乘积求和。然后调用 Reduce 来输出值。或多或少。我是 Bash 新手,所以请明确答案。

#!/bin/bash

TMPDIR=${HOME}/tmpdir

function readSeries () {
    while read -p "Enter an Integer: " number ; do
        echo $number
    done
    return 0;
} >> $$.tmp

function even-odd () {
    # unsure of how to reference TMPDIR
    while read $TMPDIR ; do
        evenp=$(($1 % 2))
        if [ $evenp -eq 0 ] ; then    # if 0 number is even
            return 0
        else                          # if 1 number is odd
            return 1
        fi
    done
}

function reduce () {
    # function to take sum of odds and product of evens
    # from lab 5 prompt
    even-odd $input
    cat $TMPDIR/$$.tmp | reduce
}

read-series

cat $TMPDIR/$$.tmp | reduce
4

1 回答 1

2

我认为这对你有用

#!/bin/bash

TMPDIR=${HOME}/tmpdir

function readSeries () {
    while read -p "Enter an Integer: " number ; do
        #
        # Using Regular Expression to ensure that value is Integer
        # If value is not integer then we return out from function
        # and won't promt again to enter
        #
        if ! [[ "$number" =~ ^[0-9]+$ ]] ; 
            then return 0;
        fi
        echo $number
    done
    return 0;
} >> $$.tmp

#function evenOdd () {
    # don't need that
#}

function reduce () {
    # function to take sum of odds and product of evens
    sumOfOdds=0;
    productOfEvens=0;

    # 
    # When a shell function is on the receiving end of a pipe, 
    # standard input is read by the first command executed inside the function. 
    # USE `read` to pull that data into function 
    # Syntax :  read variable_you_want_to_name  
    #
    while read data; do
        echo "    line by line data from tmp file "$data;
        rem=$(($data % 2))
        if [ $rem -eq 0 ] ; then    # if 0; number is even
            productOfEvens=$(($productOfEvens * $data));
        else                          # if 1; number is odd
            sumOfOdds=$(($sumOfOdds + $data));
        fi
    done

    echo " Sum of Odds    :  "$sumOfOdds;
    echo " ProductOfEvens :  "$productOfEvens;
}

readSeries

#cat $TMPDIR/$$.tmp
cat $TMPDIR/$$.tmp | reduce

或者,如果您想在此处获得更具体的答案,您必须在代码中明确,正如@shellter 指出的那样。

于 2013-10-01T07:18:23.617 回答