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

后端 未结 30 2305
猫巷女王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:24

    Have you considered just doing whatever you want to do in the if rather than looking before you leap?

    I.e., if you want to check for the existence of a directory before you enter it, try just doing this:

    if pushd /path/you/want/to/enter; then
        # Commands you want to run in this directory
        popd
    fi
    

    If the path you give to pushd exists, you'll enter it and it'll exit with 0, which means the then portion of the statement will execute. If it doesn't exist, nothing will happen (other than some output saying the directory doesn't exist, which is probably a helpful side-effect anyways for debugging).

    It seems better than this, which requires repeating yourself:

    if [ -d /path/you/want/to/enter ]; then
        pushd /path/you/want/to/enter
        # Commands you want to run in this directory
        popd
    fi
    

    The same thing works with cd, mv, rm, etc... if you try them on files that don't exist, they'll exit with an error and print a message saying it doesn't exist, and your then block will be skipped. If you try them on files that do exist, the command will execute and exit with a status of 0, allowing your then block to execute.

提交回复
热议问题