【问题标题】:Compare numbers in shell比较shell中的数字
【发布时间】:2022-10-25 00:08:05
【问题描述】:

在 shell 中比较 2 个响应代码时遇到问题。运行 curl 并需要验证响应是否在 200 到 400 之间。此外,当服务器关闭时,响应可能为“000”。

#!/bin/sh
response1="200" #curl first url
response2="000" #curl second url

if (( $response1 -ge 400 || $response1 -lt 200 || $response2 -ge 400 || $response2 -lt 200 )) ; then
  echo "Something went wrong, response code is not in success range"
  exit 1
else
  echo "Success"
  exit 0
fi

((: 200 -ge 400 || 200 -lt 200 || 000 -ge 400 || 000 -lt 200 :表达式中的语法错误(错误标记是“400 || 200 -lt 200 || 000 -ge 400 || 000 -lt 200")

如果我将括号更改为 [[...]],它总是返回 true。 如果我将 -lt 更改为 < 并将 -ge 更改为 >= ,则会出现以下错误:

((: 200 = 400 || 200 < 200 || 000 = 400 || 000 < 200 :尝试分配给非变量(错误标记是“= 400 || 200 < 200 || 000 = 400 || 000 < 200 ")

【问题讨论】:

  • (( 更改为[[(和]])。
  • ((...)) 中使用的运算符记录在 Shell Arithmetic[[...]] 中使用的运算符记录在 Bash Conditional Expressions
  • 你如何运行你的脚本?根据#!线,它不是重击脚本。

标签: linux bash shell numbers


【解决方案1】:

错误的操作员。正确的写法是:

if (( response1 > 400 || response1 < 200 || response2 > 400 || response2 < 200 )) ; then

无需使用$ 显式取消引用,只要确保您的变量仅包含整数即可。

【讨论】:

  • ((: response1 400 || response1 < 200 || response2 400 || response2 < 200 : 表达式中的语法错误(错误标记是“400 || response1 < 200 || response2 400 || response2 < 200”)
  • 当您在 if 语句前面执行 echo $BASH_VERSION 时会得到什么?
  • @MykytaShvets 从错误消息中,您在表达式的 response1 &gt; 400response2 &gt; 400 部分中缺少 &gt; 运算符。
  • 谢谢,在具有适当 bash 版本的不同环境中运行后 - 这有效
【解决方案2】:

请尝试:

if [ $response1 -ge 400 ] || [ $response1 -lt 200 ] || [ $response2 -ge 400 
 ] || [ $response2 -lt 200 ] ; then
  echo "Something went wrong, response code is not in success range"
  exit 1
else
  echo "Success"
  exit 0
fi

【讨论】:

    猜你喜欢
    • 2013-12-10
    • 2016-01-16
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多