bash - 在 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
如何解决此错误?我究竟做错了什么?
解决方案
给你,正则表达式为我工作:
#!/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
推荐阅读
- c# - xml序列化添加元素的属性
- pymatgen - 从 pymatgen 结构对象中提取坐标和原子类型
- r - 将 grepl 与 paste 一起使用时出现错误。无效的正则表达式
- angularjs - 当 0 索引上没有数据时显示错误
- xcode - Xcode 10/11 中的 UI 测试特定 GPX 文件
- python-3.x - 无法在 selenium python 中打印选择中的选项文本
- c - 将除以零定义为无穷大
- reactjs - 启动时创建反应应用程序“编译失败”
- python - 使用 oracle 客户端和带有 Python 的 kerberos 连接到数据库
- css - CSS 选择器传递部分标签名称以查找元素