Linux bash 中的條件程式碼區塊

Linux bash 中的條件程式碼區塊

幾乎每個人都知道非常有用的 && 和 ||運算符,例如:

rm myf && echo "File is removed successfully" || echo "File is not removed"

我有一個問題:如何在 && 或 || 之後放置命令塊不使用函數的運算子?

例如我想做:

rm myf && \
  echo "File is removed successfully" \
  echo "another command executed when rm was successful" || \
  echo "File is not removed" \
  echo "another command executed when rm was NOT successful"

該腳本的正確語法是什麼?

答案1

rm myf && {
  echo "File is removed successfully" 
  echo "another command executed when rm was successful"
} || {
  echo "File is not removed" 
  echo "another command executed when rm was NOT successful"
}

或更好

if  rm myf ; then
      echo "File is removed successfully" 
      echo "another command executed when rm was successful"
else
      echo "File is not removed" 
      echo "another command executed when rm was NOT successful"
fi

相關內容