shell检查目录路径是否存在

为了检查linux中文件目录是否存在,可以使用以下命令:

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

但是对于符号链接,可能会出错:

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