How can I check if a directory exists in a Bash shell script?

后端 未结 30 2318
猫巷女王i
猫巷女王i 2020-11-22 10:35

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

30条回答
  •  故里飘歌
    2020-11-22 11:16

    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".

提交回复
热议问题