在bash函数中使用管道和egrep

时间:2018-09-11 20:18:46

标签: bash grep pipe

我创建了一个函数,要求用户猜测目录中有多少个文件,并且我正在尝试检查输入是否有效。对于第18行,我试图检查输入是否包含单词,如果包含,请告知用户这不是有效的输入。但是,我收到以下错误:

guessinggame.sh: line 18: conditional binary operator expected
guessinggame.sh: line 18: syntax error near `$response'
guessinggame.sh: line 18: `    elif [[ echo $response | egrep "\w" response.txt ]'

这是我的代码:

function guessinggame {
num_input=true
while $num_input
do
  echo 'Guess how many files are in the current directory. Type in a number and 
        then press Enter:'
  read response
  echo $response > response.txt
  if [[ $response -eq 3 ]]
  then
    echo 'Congratulations! You guessed correctly!'
    num_input=false
  elif [[ $response -gt 3 ]]
  then
    echo '$response is too high! Guess again.'
  elif [[ $response -lt 3 ]]
  then
    echo '$response is too low! Guess again.'
  elif [[ echo $response | egrep "\w" response.txt ]]
  then
    echo '$response is not a number! Please enter a valid input.'
  else
    echo '$response is not a number! Please enter a valid input.'
  fi
num_input=$num_input
done
}
guessinggame

如何解决此错误?我在做什么错了?

1 个答案:

答案 0 :(得分:4)

在这里,正则表达式为我工作:

#!/bin/bash
guessinggame() {
  local num_input response
  num_input=1
  while (( num_input )); do 
    echo 'Guess how many files are in the current directory. Type in a number and 
          then press Enter:'
    read -r response
    echo "$response" > response.txt

    if ! [[ "$response" =~ ^[0-9]+$ ]]; then
      echo "$response is not a number! Please enter a valid input."
    elif (( response == 3 )); then
      echo 'Congratulations! You guessed correctly!'
      num_input=0
    elif (( response > 3 )); then
      echo "$response is too high! Guess again."
    elif (( response < 3 )); then
      echo "$response is too low! Guess again."
    else
      echo "$response is not a number! Please enter a valid input."
    fi
    num_input=$num_input
  done
}

guessinggame