Check if a directory exists in a shell script

2018-12-31 14:29发布

What command can be used to check if a directory exists or not, within a shell script?

标签: shell unix posix
30条回答
刘海飞了
2楼-- · 2018-12-31 14:58

This answer wrapped up as a shell script

Examples

$ is_dir ~                           
YES

$ is_dir /tmp                        
YES

$ is_dir ~/bin                       
YES

$ mkdir '/tmp/test me'

$ is_dir '/tmp/test me'
YES

$ is_dir /asdf/asdf                  
NO

# Example of calling it in another script
DIR=~/mydata
if [ $(is_dir $DIR) == "NO" ]
then
  echo "Folder doesnt exist: $DIR";
  exit;
fi

is_dir

function show_help()
{
  IT=$(CAT <<EOF

  usage: DIR
  output: YES or NO, depending on whether or not the directory exists.

  )
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

DIR=$1
if [ -d $DIR ]; then 
   echo "YES";
   exit;
fi
echo "NO";
查看更多
泛滥B
3楼-- · 2018-12-31 14:58

Using the -e check will check for files and this includes directories.

if [ -e ${FILE_PATH_AND_NAME} ]
then
    echo "The file or directory exists."
fi
查看更多
闭嘴吧你
4楼-- · 2018-12-31 14:58
file="foo" 
if [[ -e "$file" ]]; then echo "File Exists"; fi;
查看更多
流年柔荑漫光年
5楼-- · 2018-12-31 15:01

Check if directory exists, else make one

[ -d "$DIRECTORY" ] || mkdir $DIRECTORY
查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 15:02

If you want to check if a directory exists, regardless if it's a real directory or a symlink, use this:

ls $DIR
if [ $? != 0 ]; then
        echo "Directory $DIR already exists!"
        exit 1;
fi
echo "Directory $DIR does not exist..."

Explanation: The "ls" command gives an error "ls: /x: No such file or directory" if the directory or symlink does not exist, and also sets the return code, which you can retrieve via "$?", to non-null (normally "1"). Be sure that you check the return code directly after calling "ls".

查看更多
萌妹纸的霸气范
7楼-- · 2018-12-31 15:02

(1)

[ -d Piyush_Drv1 ] && echo ""Exists"" || echo "Not Exists"

(2)

[ `find . -type d -name Piyush_Drv1 -print | wc -l` -eq 1 ] && echo Exists || echo "Not Exists"

(3)

[[ -d run_dir  && ! -L run_dir ]] && echo Exists || echo "Not Exists"

If found an issue with one of the approach provided above.

With ls command; the cases when directory does not exists - an error message is shown

$ [[ ls -ld SAMPLE_DIR| grep ^d | wc -l -eq 1 ]] && echo exists || not exists -ksh: not: not found [No such file or directory]

查看更多
登录 后发表回答