【发布时间】:2019-02-16 09:57:18
【问题描述】:
我创建了一个函数,要求用户猜测目录中有多少文件,并且我正在尝试检查输入是否有效。对于第 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
如何解决此错误?我做错了什么?
【问题讨论】:
-
将其粘贴到shellcheck.net 并修复它告诉您的所有内容。您缺少右引号,
[[ ... ]]中缺少右引号],包含变量的单引号字符串... -
另外,
num_input=$num_input什么也没做。 -
使用
echo text | grep ...或grep ... file,但不能使用echo text | grep ... file。删除[[ ]]大括号并添加-q:elif ... grep -Eq ...。 -
您还在尝试将这些内容放入
[[ ]]中吗?[[是扩展的test命令。echo和grep都不是test的参数,无论是扩展的还是其他的——所以你可以运行if echo foo | grep,但不能写if [[ echo foo | grep ]]。 -
...也就是说
[[是一个命令,它不是if语法的一部分。