newb的基本Bash脚本

时间:2013-10-01 00:35:41

标签: bash shell

这是我的代码:我想在临时目录中创建一个临时变量。我创建了一个名为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

1 个答案:

答案 0 :(得分: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指出。