首页 > 解决方案 > if else 语句 bash 脚本

问题描述

我不确定为什么我的脚本总是执行最后一条语句,即使文件 file1 和 file2 不为空:

SERVER_NAME=$HOSTNAME
SENDER="Admin"
SUBJECT="Notification from "$SERVER_NAME""
RECEIVER="admin@mycompany.com"
file1=/home/first_file.txt 
file2=/home/second_file.txt
TEXT1="The file $file1 is empty"
TEXT2="The file $file2 is empty"
TEXT3="Both files are empty"


if [ -s $file1 && -s $file2 ]
     then
        echo "files are good"  

    elif [[ -s $file1 ]]
     then
        echo -e "$TEXT2" | mail -s "$SUBJECT" "$RECEIVER" &>/dev/null

    elif [[ -s $file2 ]]
    then
        echo -e "$TEXT1" | mail -s "$SUBJECT" "$RECEIVER"  &>/dev/null

    else
        echo -e "$TEXT3" | mail -s "$SUBJECT" "$RECEIVER"  &>/dev/null

    fi

要求是在一个或两个文件为空时发送通知

标签: bashif-statement

解决方案


这是一个供参考的工作脚本。

SERVER_NAME=$HOSTNAME
SENDER="Admin"
SUBJECT="Notification from "$SERVER_NAME""
RECEIVER="admin@mycompany.com"
file1=/home/first_file.txt 
file2=/home/second_file.txt
TEXT1="The file $file1 is empty"
TEXT2="The file $file2 is empty"
TEXT3="Both files are empty"


if [[ -s $file1 && -s $file2 ]]
     then
        echo "files are good"  

    elif [[ -s $file1 ]]
     then
        echo -e "$TEXT2" | mail -s "$SUBJECT" "$RECEIVER" &>/dev/null

    elif [[ -s $file2 ]]
    then
        echo -e "$TEXT1" | mail -s "$SUBJECT" "$RECEIVER"  &>/dev/null

    else
        echo -e "$TEXT3" | mail -s "$SUBJECT" "$RECEIVER"  &>/dev/null

    fi

推荐阅读