2013-10-01 97 views
1

這是我的代碼:我想在一個臨時目錄中創建一個臨時變量。我創建了一個名爲read-series的函數,它讀取整數直到ctrl-d,然後將它們附加到.tmp。然後它傳遞到偶數和總和的機率之和。然後調用Reduce來輸出值。或多或少。我是Bash的新手,所以請在回答中明確。newb的基本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 
+0

如果你想得到明確的答案,你必須清楚你的代碼。例如,「read-series」定義在哪裏(即在腳本的第二行到最後一行),並在'reduce'函數內調用'reduce'會導致問題。學習理解在代碼頂部附近添加'set -x'的輸出對於調試你自己的代碼是一個很大的幫助。祝你好運。 – shellter

回答

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指出更具體的答案。