0

我正在使用 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
4

3 回答 3

4

这条线

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

尝试执行名为“播客已同步”的命令。(没有引号,但它们之间的所有内容),并将其输出传递给“邮件”命令。令牌“success_message=echo”导致在“Podcasts are 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
于 2013-10-16T02:14:57.483 回答
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
于 2013-10-16T02:12:42.280 回答
1

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

success_message=echo "Podcasts are synced." | mail -s "Your podcasts have been synced to   your phone." $email_address
于 2013-10-16T02:11:10.413 回答