【问题标题】:Shell script if statement always executes else blockShell 脚本 if 语句总是执行 else 块
【发布时间】:2022-01-05 13:14:26
【问题描述】:

我写了一个简单的if-else 语句,并从 cronjob 调用它。

cronscript.sh

#!/bin/sh

# Author : TEST USER
# Script follows here:
VAR1="-h"
VAR2="-h"
if [[ "$VAR1" == "$VAR2" ]]; then
    echo "Strings are equal."
else
    echo "Strings are not equal."
fi

我总是得到输出 Strings are not equal.即使两个字符串都一样,为什么要执行 ELSE 块?

cronjob 命令

34 18 05 * * /var/www/html/cronscript.sh > /var/www/html/testcron.txt

cronjob 正在正常执行,输出存储在 testcron.txt 文件中。

【问题讨论】:

  • 你使用dash作为/bin/sh吗?
  • 如果您将脚本粘贴到 shellcheck,您将收到警告 SC3010 (warning): In POSIX sh, [[ ]] is undefined.

标签: bash shell if-statement


【解决方案1】:

您的脚本有shebang #!/bin/sh 并尝试使用[[,这是特定于bash 的语法。你应该改变shebang:

#!/bin/bash

或者使用普通的 POSIX sh 条件语法:

if [ "$VAR1" = "$VAR2" ]; then

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多