Bash:语法错误 - 令牌“else”附近出现意外

Bash:语法错误 - 令牌“else”附近出现意外

好吧,我完全不明白为什么 bash 会向我抛出这个错误。我创建了一个脚本来检查驱动器是否安装在目录中。如果安装了驱动器,它会执行一些 rsync 任务(并将状态打印到日志中)。如果它没有安装,它应该给我发电子邮件(从代码中编辑的邮件)。

但每当我运行此代码时,它都会向我抛出“语法错误:‘else’附近出现意外标记”。为什么会出现这个语法错误?

我尝试使用 1 [ en 2 [[ 和 f 语句,在 sudo 下运行脚本,但没有骰子。

在代码中添加了额外的注释,以便您可以看到逻辑;)。

#!/bin/bash
#Print to log that check is starting
printf "Checking if Backup drive is successfully mounted\n" >>/home/fileserver/Applications/Backup/logs/backup.log 2>&1 &&

# Start check
if [[ $(mount | grep -c /home/fileserver/Backup4TB) != 0 ]]; then

# If check is successfull, print it to log & start the backup
printf "Backup Drive successfully mounted, Backing up Applications folder to USB Backup Drive\n" >>/home/fileserver/Applications/Backup/logs/backup.log 2>&1 &&

# Backup using rsync
rsync --log-file=/home/fileserver/Applications/Backup/logs/rsync.log -avhP --delete /home/fileserver/Applications/ /home/fileserver/Backup4TB/Applications >/dev/null 2>&1 &&

# Print to log
printf "Backing up Books folder to USB Backup Drive\n" >>/home/fileserver/Applications/Backup/logs/backup.log 2>&1 &&

# Backup using rsync
rsync --log-file=/home/fileserver/Applications/Backup/logs/rsync.log -avhP --delete /home/fileserver/Media/Books/ /home/fileserver/Backup4TB/Books >/dev/null 2>&1 &&

# SYNTAX ERROR IS HERE - If check is unsuccessfull
else

# Print error to log
printf "ERROR - Mount was insuccesfull, sending email as warning\n" >>/home/fileserver/Applications/Backup/logs/backup.log 2>&1 &&

# Email me
/usr/sbin/ssmtp "MYEMAIL" < /home/fileserver/Applications/Backup/mountingerror/mountingerrorBackup.txt

fi

答案1

是的,找到了:我将 && 放在最后一个命令之后,就在 else 语句之前:

...

# Backup using rsync
rsync --log-file=/home/fileserver/Applications/Backup/logs/rsync.log -avhP --delete /home/fileserver/Media/Books/ /home/fileserver/Backup4TB/Books >/dev/null 2>&1 &&

# SYNTAX ERROR IS HERE - If check is unsuccessfull
else

...

通过删除 &&,错误消失:

...

# Backup using rsync
rsync --log-file=/home/fileserver/Applications/Backup/logs/rsync.log -avhP --delete /home/fileserver/Media/Books/ /home/fileserver/Backup4TB/Books >/dev/null 2>&1 

# SYNTAX ERROR IS HERE - If check is unsuccessfull
else

...

相关内容