在for循环中使用管道。如何在for循环中保留变量的值

时间:2016-04-04 16:23:34

标签: bash shell for-loop

我已经被以下代码困住了一段时间。它可以工作,但变量会丢失在迭代期间设置的值。

我有以下代码

  mistakes=0
  entered_chars=()


 word_length=0
 answer=""
 answer_guess=""


checkIfLetterInsideWord(){

exists=0
letter=$2

    word_array=`echo $1 | grep -o . `;

for (( i=1; i <= $word_length; i++))
    do
       if [[ "${1:$i-1:1}" = ${letter} ]]; then

          exists=1

          answer_guess=$(echo $answer_guess | sed "s/-/${letter}/{i}" )

       fi

 done

 echo $exists

}

askUserInput(){

    answer=$answer
    echo $answer
    echo "Please type a letter"
    read user_input


    if [ ! -z $user_input ]; then

    user_input=$(echo $user_input | tr '[:upper:]' '[:lower:]')

     if [ $(checkIfAlreadyEntered "$user_input") -eq 0 ]; then

        if [ $(checkIfLetterInsideWord $answer $user_input) -eq 0 ]; then 
        mistakes=$((mistakes + 1)); fi

        echo "Current mistake count; $mistakes "

        entered_chars+=($user_input)

    else
        echo "Char has already been entered"
    fi
else
    echo "You haven't entered any input!"
fi

}


guessTheWord() {

answer=$OPTARG
word_length=$(printf $answer | wc -m)

temp=$(echo $answer | sed 's/\(.\)/\1 /g')
array=($temp)


echo "The chosen word is $word_length long" 

gameOngoing=true


      for(( i=1; i<=$word_length; i++)) do
            answer_guess="$answer_guess-"
     done



while $gameOngoing
 do

echo $answer_guess

askUserInput $answer    



done




 }

我想保留变量answer_guess的值。我知道它因为在循环中使用了一个管道而失去了价值,但我不知道要解决这个问题。

2 个答案:

答案 0 :(得分:2)

The problem has nothing do to with the pipe. Rather, it is that you call checkIfLetterInsideWord inside a command-substitution ($(...)). Command substitution executes in a subshell so environment changes in the function will not persist.

It would be better to rewrite checkIfLetterInsideWord so that it returns an exit status. Something like:

if [[ $exists ]]; then
  return 0 # Success
else
  return 1 # Failure
end

Then you could simply call it without worrying about a subshell:

if checkIfLetterInsideWord "$answer" "$user_input"; then
  # letter is in word
else
  # letter is not in word
fi

There are other issues with the code. I've limited this answer to the question about preserving the value of variables.

答案 1 :(得分:0)

answer_guess=$(echo $answer_guess | sed "s/-/${letter}/{i}" )

replace the - with .

so your code becomes

answer_guess=$(echo $answer_guess | sed "s/./${letter}/{i}" )