rmdir: failed to remove `symlink': Not a directory
因此,如果后续命令需要目录,则符号链接可能必须区别对待:
if [ -d "$LINK_OR_DIR" ]; thenif [ -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"fifi
found=`find -type d -name "myDirectory"`if [ -n "$found" ]then# The variable 'found' contains the full path where "myDirectory" is.# It may contain several lines if there are several folders named "myDirectory".fi
根据当前目录中的模式检查一个或多个文件夹的存在:
found=`find -maxdepth 1 -type d -name "my*"`if [ -n "$found" ]then# The variable 'found' contains the full path where folders "my*" have been found.fi
两种组合。在以下示例中,它检查当前目录中文件夹的存在:
found=`find -maxdepth 1 -type d -name "myDirectory"`if [ -n "$found" ]then# The variable 'found' is not empty => "myDirectory"` exists.fi
DIR_PATH=`readlink -f "${the_stuff_you_test}"` # Get rid of symlinks and get abs pathif [[ -d "${DIR_PATH}" ]] ; Then # Now you're testingecho "It's a dir";fi
if [ -d "$DIRECTORY" ]; then# Will enter here if $DIRECTORY existsfi
这并非完全正确……
如果您想访问该目录,您还需要对该目录拥有执行权限。也许您还需要写入权限。
因此:
if [ -d "$DIRECTORY" ] && [ -x "$DIRECTORY" ] ; then# ... to go to that directory (even if DIRECTORY is a link)cd $DIRECTORYpwdfi
if [ -d "$DIRECTORY" ] && [ -w "$DIRECTORY" ] ; then# ... to go to that directory and write something there (even if DIRECTORY is a link)cd $DIRECTORYtouch foobarfi
[[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] &&echo "YES, $ISDIR is a directory." ||echo "Sorry, $ISDIR is not a directory"
实际用法:
[claudio@nowhere ~]$ ISDIR="$HOME/Music"[claudio@nowhere ~]$ ls -ld "$ISDIR"drwxr-xr-x. 2 claudio claudio 4096 Aug 23 00:02 /home/claudio/Music[claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] &&echo "YES, $ISDIR is a directory." ||echo "Sorry, $ISDIR is not a directory"YES, /home/claudio/Music is a directory.
[claudio@nowhere ~]$ touch "empty file.txt"[claudio@nowhere ~]$ ISDIR="$HOME/empty file.txt"[claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] &&echo "YES, $ISDIR is a directory." ||echo "Sorry, $ISDIR is not a directoy"Sorry, /home/claudio/empty file.txt is not a directory
if [ -d "$LINK_OR_DIR" ]; thenif [ -L "$LINK_OR_DIR" ]; then# It is a symlink!# Symbolic link specific commands go hererm "$LINK_OR_DIR"else# It's a directory!# Directory command goes herermdir "$LINK_OR_DIR"fifi
$ is_dir ~YES
$ is_dir /tmpYES
$ is_dir ~/binYES
$ mkdir '/tmp/test me'
$ is_dir '/tmp/test me'YES
$ is_dir /asdf/asdfNO
# Example of calling it in another scriptDIR=~/mydataif [ $(is_dir $DIR) == "NO" ]thenecho "Folder doesnt exist: $DIR";exit;fi
is_dir
function show_help(){IT=$(CAT <<EOF
usage: DIRoutput: YES or NO, depending on whether or not the directory exists.
)echo "$IT"exit}
if [ "$1" == "help" ]thenshow_helpfiif [ -z "$1" ]thenshow_helpfi
DIR=$1if [ -d $DIR ]; thenecho "YES";exit;fiecho "NO";