【问题标题】:Multiple conditions in case statement, bashcase语句中的多个条件,bash
【发布时间】:2020-06-20 21:46:23
【问题描述】:
read X;
read Y;
read Z;
if [[ $X,$Y,$Z -ne "0" ]]; then
  if [[ $X,$Y,$Z -ge 1 && $X,$Y,$Z -le 1000 ]] && [[ $((X+Y)) -gt $Z || $((Y+Z)) -gt $X || $((X+Z)) -gt $Y ]]; then
    case $X,$Y,$Z in
      $X -eq $Y && $Y -eq $Z && $X -eq $Z ) echo "EQUILATERAL";;

    esac
  else
    echo "bye";
  fi
fi

*./bashtesting.sh:第 7 行:意外标记 `-eq 附近的语法错误

./bashtesting.sh: 第 7 行: $X -eq $Y && $Y -eq $Z && $X -eq $Z ) echo "EQUILATERAL";;*


如何一次将三个变量等同起来?

【问题讨论】:

  • 我建议将[[ $X,$Y,$Z -ne "0" ]]替换为[[ $X -ne 0 ]] && [[ $Y -ne 0 ]] && [[ $Z -ne 0 ]]

标签: linux bash syntax


【解决方案1】:

这就是我的做法,使用循环和关联数组。

#!/usr/bin/env bash

for h in x y z; do
  read -rp 'Enter input: ' input
  if [[ -z $input ]]; then
    printf >&2 '%s is empty, please try again!\n' "${input:-input}"
    exit 1
  elif [[ $input != *[0-9]* ]]; then
    printf '%s is not an int, please try again!\n' "$input"
    exit 1
  else
    declare -A num[$h]=$input
  fi
done

for i in "${num[@]}"; do
  if ! (( i == 0 )); then
    for j in "${num[@]}"; do
      if (( j > 1 && j < 100 )); then
        if (( (num[x] + num[y]) > num[z] || (num[y] + num[z]) > num[x] || (num[x] + num[z]) > num[y] )); then
          if (( num[x] == num[y] && num[y] == num[x] && num[x] == num[z] )); then
            echo equilateral
            break 2
          fi
        fi
      fi
    done
  fi
done
  • 它不漂亮,看起来像 Anti Pattern,可能有更好的方法,但我想这会让你到达那里。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多