What command can be used to check if a directory exists or not, within a Bash shell script?
Bash - How to check if a directory exists in a Bash shell script
bashposixshellunix
Related Question
- Bash - How to get the source directory of a Bash script from within the script itself
- Python - How to execute a program or call a system command
- Linux - How to prompt for Yes/No/Cancel input in a Linux shell script
- Json - How to pretty-print JSON in a shell script
- Bash - How to check if a program exists from a Bash script
- Bash - How to tell if a regular file does not exist in Bash
- How to mkdir only if a directory does not already exist
- Bash - In the shell, what does ” 2>&1 ” mean
- Bash - How to set a variable to the output of a command in Bash
- Bash - Check existence of input argument in a Bash shell script
Best Solution
To check if a directory exists in a shell script, you can use the following:
Or to check if a directory doesn't exist:
However, as Jon Ericson points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check. E.g. running this:
Will produce the error message:
So symbolic links may have to be treated differently, if subsequent commands expect directories:
Take particular note of the double-quotes used to wrap the variables. The reason for this is explained by 8jean in another answer.
If the variables contain spaces or other unusual characters it will probably cause the script to fail.