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

...

相關內容