bash - BASH——复杂的比较
问题描述
代码采用三个变量并检查其中两个是否相同但第三个不同,如果是这种情况,那么它将报告这些变量组成一个等腰三角形所以我已经安排如果 $s1s2 为真表示 $s1 等于 $s2
if [ $s1s2 && $s2s3 !&& $s1s3 ] || [ $s1s2 && $s1s3 !&& $s2s3 ] || [ $s2s3 && $s1s3 !&& $s1s2 ] = true
then isostri = True
else isostri = false
fi
我只是在学习我的基础并且很困惑为什么上面的代码不起作用。我努力了:
- 将整个系列包装在括号的超集中,并保持它们独立
- 我玩过布尔指示符的区分大小写
- 我尝试将布尔值单独分配给集合
- 我还尝试将这些 OR 语句分成三个单独的 IF 子句
Shellcheck 说:
Line 1:
if [ $s1s2 && $s2s3 !&& $s1s3 ] || [ $s1s2 && $s1s3 !&& $s2s3 ] || [ $s2s3 && $s1s3 !&& $s1s2 ] = true
^-- SC1009: The mentioned syntax error was in this if expression.
^-- SC1073: Couldn't parse this test expression. Fix to allow more checks.
^-- SC1072: Expected test to end here (don't wrap commands in []/[[]]). Fix any mentioned problems and try again.
这是整个代码,自开始发布这篇文章以来进行了一些额外的调整:
read X
read Y
read Z
s1 = $X
s2 = $Y
s3 = $Z
if s1 -eq s2
then s1s2 = true
else s1s2 = false
fi
if s2 -eq s3
then s2s3 = true
else s2s3 = false
fi
if s1 -eq s3
then s1s3 = true
else s1s3 = false
fi
if [ $s1s2 && $s2s3 && $s1s3 ] = true
then equatri = true
else equatri = false
fi
if [ [ $s1s2 -eq $s2s3 ] && [ $s1s2 -ne $s1s3 ] ] || [ [ $s1s2 -eq $s1s3 ] && [ $s1s2 -ne $s2s3 ] || [ [ $s2s3 -eq $s1s3 ] && [ $s2s3 -ne $s1s2 ] ] = true
then isostri = true
else isostri = false
fi
if [ $s1s2 && $s2s3 && $s2s3] = false
then scaltri = true
fi
if $equatri = true
then
echo "EQUILATERAL"
elif $isostri = true
then
echo "ISOSCELES"
elif $scaltri = true
then
echo "SCALENE"
fi
解决了!谢谢大家的帮助。评论指出了一些我不知道的缺陷,而答案都帮助我理解了我的逻辑过于复杂。我试图检查两种情况的真实性,然后验证第三种情况为假。但我现在看到发生了假设的双条件事情,只要检查以正确的顺序流动,我就可以忽略第三种情况(从最多检查到最少),这使我可以将等腰计算减少到对两侧的多个比较。
这是混乱的质量已减少到的内容:
read X
read Y
read Z
s1=$X
s2=$Y
s3=$Z
if [ $s1 == $s2 ] && [ $s1 == $s3 ]; then echo "EQUILATERAL"
elif [ $s1 -eq $s2 ]; then echo "ISOSCELES"
elif [ $s2 -eq $s3 ]; then echo "ISOSCELES"
elif [ $s1 -eq $s3 ]; then echo "ISOSCELES"
else echo "SCALENE"
fi
解决方案
这个问题有很多解决方案(识别bash中的三角形类型),搜索isosceles bash
:https ://stackoverflow.com/search?q=isosceles+bash
简单一:
#!/bin/bash
read a b c
if [ "$a" -eq "$b" ] && [ "$b" -eq "$c" ] ; then
echo "EQUILATERAL"
elif [ "$a" -eq "$b" ] || [ "$b" -eq "$c" ] || [ "$c" -eq "$a" ]; then
echo "ISOSCELES"
then
echo "SCALENE"
fi
推荐阅读
- docker - Docker:“/var/cache/apt/archives/ 中没有足够的可用空间”
- algorithm - 需要一种算法来“均匀地”迭代一组值的所有可能组合
- android - 重复请求 X 次或直到返回 Y 个项目
- c# - 如何在 Docker 容器中同时安装 MATLAB MCR 和 dotnet 运行时?
- python - 解析数据并从文本中获取变量
- javascript - 使用 javascript 创建组合框时遇到问题
- ios - 如何从 UINIbDecoder 推断 .xib 文件?
- ruby-on-rails - Rails StimulusJS 控制器未在生产中连接
- mysql - 三张表 - 两张相同,一张带有标识符,MySQL - 检索行
- postgresql - 有没有办法使用 Sequelize for Postgres 进行表锁定?