如果大于或等于错误,则 bash



使用下面的 bash 脚本,我收到一个错误;

line 16: [: : integer expression expected,但我不知道为什么?错误在于if [ "$(log_date)" -le "$days_in_ms" ]; then如果陈述让我感到困惑,任何人都可以帮助并解释为 BASH

#!/bin/bash
region="eu-west-1"
retention_days="28"
days_in_ms="$(date +%s%3N --date=-"$retention_days"+days)"
log_date () {
  aws logs describe-log-streams --region $region --log-group-name "$groups" | jq -r '.logStreams[].lastEventTimestamp' > /dev/null 2>&1
}
log_name () {
  aws logs describe-log-streams --region $region --log-group-name "$groups" | jq -r '.logStreams[].logStreamName' > /dev/null 2>&1
}
mapfile -t logGroups < <(aws logs describe-log-groups --region $region | jq -r '.logGroups[].logGroupName') > /dev/null 2>&1
for groups in "${logGroups[@]}"; do
    if [ "$(log_date)" -le "$days_in_ms" ]; then
        log_name
     fi
done
发生了什么

请注意错误消息的详细信息:

[: : integer expression expected

看到第二个:之前的空白吗?这就是[试图操作的价值所在,如果有的话。它是空白的,这意味着[被告知会是一个数字的东西根本不存在。

要提供其工作原理的示例:

$ [ foo -ge 1 ]
-bash: [: foo: integer expression expected

请注意,foo是在空白的相同位置给出的。因此,空白值被解析为数字。


为什么会这样

您的log_date函数不返回任何输出,因为它>/dev/null .因此,您的代码尝试将它返回的空字符串解析为数字,并(正确(抱怨它在需要整数的位置获取空字符串。

将来,请运行 set -x 以在运行每个命令之前启用其日志记录,或者在调试时使用bash -x yourscript调用脚本,以识别这些问题。

最新更新