What command can be used to check if a directory exists or not, within a Bash shell script?
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.