为什么这个bash“if”语句执行两个语句

时间:2013-10-16 02:07:13

标签: bash if-statement rsync

我正在使用rsync脚本来将某些内容同步到我的手机上。我正在尝试编写一个if语句来决定在命令完成时我在电子邮件中收到哪条消息。出于某种原因,无论命令如何退出,我都会收到这两封电子邮件。

success_message=echo "Podcasts are synced." | mail -s "Your podcasts have been synced to   your phone." $email_address
fail_message=echo "Your phone did not sync." | mail -s "For some reason, your podcasts did not sync today." $email_address

rsync --log-file=/home/jake/logs/rsync.log -avzu $local_directory $remote_directory
if [ $? -ne "0" ];
then
  $fail_message
else
  $success_message
fi

3 个答案:

答案 0 :(得分:4)

这一行

success_message=echo "Podcasts are synced." | mail ...

尝试执行名为的命令“播客已同步。” (没有引号,但它们之间有一切),并将其输出传递给“mail”命令。令牌“success_message = echo”导致在“Podcasts is synced”的环境中设置名为“success_message”的环境变量。命令,值为“echo”。

重要的是,即使管道左侧的东西都失败了(因为你没有名为/usr/bin/Podcasts are synced.的程序,毫无疑问),mail执行右边的命令。由于有两条这样的行,两个命令都会运行。

以下是如何做你想做的事情:

send_success_message () {
    echo "Podcasts are synced." | 
        mail -s "Your podcasts have been synced to your phone." "$1"
}
send_fail_message () {
    echo "Your phone did not sync." |
        mail -s "For some reason, your podcasts did not sync today." "$1"
}

if rsync --log-file=/home/jake/logs/rsync.log -avzu \
         "$local_directory" "$remote_directory"
then send_success_message "$email_address"
else send_fail_message "$email_address"
fi

答案 1 :(得分:1)

此行发送消息,因为第一条指令在管道处结束。

success_message=echo "Podcasts are synced." | mail -s "Your podcasts have been synced to   your phone." $email_address

答案 2 :(得分:1)

尝试将命令放入shell变量然后再引用一次变量绝对没有任何好处。只需将命令放在if语句中:

rsync --log-file=/home/jake/logs/rsync.log -avzu $local_directory $remote_directory

if [ $? -ne "0" ];
then
    echo "Podcasts are synced." | mail -s "Your podcasts have been synced to   your phone." $email_address
else
    echo "Your phone did not sync." | mail -s "For some reason, your podcasts did not sync today." $email_address
fi