首页 > 解决方案 > BASH——复杂的比较

问题描述

代码采用三个变量并检查其中两个是否相同但第三个不同,如果是这种情况,那么它将报告这些变量组成一个等腰三角形所以我已经安排如果 $s1s2 为真表示 $s1 等于 $s2

if [ $s1s2 && $s2s3 !&& $s1s3 ] || [ $s1s2 && $s1s3 !&& $s2s3 ] || [ $s2s3 && $s1s3 !&& $s1s2 ] = true
     then isostri = True
    else isostri = false
    fi

我只是在学习我的基础并且很困惑为什么上面的代码不起作用。我努力了:

  1. 将整个系列包装在括号的超集中,并保持它们独立
  2. 我玩过布尔指示符的区分大小写
  3. 我尝试将布尔值单独分配给集合
  4. 我还尝试将这些 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

标签: bashcomparison

解决方案


这个问题有很多解决方案(识别bash中的三角形类型),搜索isosceles bashhttps ://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

推荐阅读