简体   繁体   English

Shell 脚本 if 语句总是执行 else 块

[英]Shell script if statement always executes else block

I have written a simple if - else statement and am calling it from cronjob.我写了一个简单的if - else语句,并从 cronjob 中调用它。

cronscript.sh 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

I'm always getting output as Strings are not equal.我总是得到 output 因为Strings are not equal. Even though both strings are same why it is executing ELSE block?即使两个字符串都相同,为什么它正在执行 ELSE 块?

cronjob command cronjob 命令

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

cronjob is executing properly and output is stored in testcron.txt file. cronjob 正常执行,output 存储在 testcron.txt 文件中。

Your script has the shebang #!/bin/sh and tries to use [[ , which is bash-specific syntax.您的脚本具有 shebang #!/bin/sh并尝试使用[[ ,这是特定于 bash 的语法。 You should either change the shebang:您应该更改 shebang:

#!/bin/bash

Or use plain POSIX sh conditional syntax:或者使用普通的 POSIX sh 条件语法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM