在shell指令碼中,可以使用什麼命令來檢查目錄是否存在?
最佳答案
要檢查shell指令碼中是否存在目錄,您可以使用以下內容:
if [ -d "$DIRECTORY" ]; then
# Control will enter here if $DIRECTORY exists.
fi
或者檢查目錄是否不存在:
if [ ! -d "$DIRECTORY" ]; then
# Control will enter here if $DIRECTORY doesn't exist.
fi
但是,正如 Jon Ericson 所指出,如果您不考慮到目錄的符號連結也會傳遞此檢查,後續命令可能無法正常工作。 例如執行此:
ln -s "$ACTUAL_DIR" "$SYMLINK"
if [ -d "$SYMLINK" ]; then
rmdir "$SYMLINK"
fi
將生成錯誤訊息:
rmdir: failed to remove `symlink': Not a directory
因此,如果後續命令期望目錄,則可能需要對符號連結進行不同的處理:
if [ -d "$LINK_OR_DIR" ]; then
if [ -L "$LINK_OR_DIR" ]; then
# It is a symlink!
# Symbolic link specific commands go here.
rm "$LINK_OR_DIR"
else
# It's a directory!
# Directory command goes here.
rmdir "$LINK_OR_DIR"
fi
fi
特別注意用於包裝變數的雙引號,原因是8jean 在另一個答案中解釋了這一點。
如果變數包含空格或其他異常字元,它可能會導致指令碼失敗。
上一個問題:在C中建立稀疏陣列的最佳方法是什麼?
下一個問題:Grid Hosting for Windows