首页 > 解决方案 > 在 bash 函数中使用管道和 egrep

问题描述

我创建了一个函数,要求用户猜测目录中有多少文件,并且我正在尝试检查输入是否有效。对于第 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

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

标签: bashgreppipe

解决方案


给你,正则表达式为我工作:

#!/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

推荐阅读