To check if a directory exists in a Linux or Unix shell, you can use the test
command with the -d
option. The test
command is a utility that allows you to perform various tests on files and directories, and the -d
option tells the test
command to check if a file is a directory.
To check if a directory exists, use the following syntax:
test -d directory
Replace directory
with the name of the directory that you want to check. For example, to check if the /tmp
directory exists, you would use the following command:
test -d /tmp
If the directory exists, the test
command will return a zero exit code, which indicates success. If the directory does not exist, the test
command will return a non-zero exit code, which indicates failure.
You can use the test
command in a shell script or in a shell command line to check the existence of a directory and perform different actions based on the result. For example, you can use the if
statement to check the result of the test
command and execute different commands depending on whether the directory exists or not:
if test -d /tmp; then echo "The /tmp directory exists." else echo "The /tmp directory does not exist." fi
This script will check if the /tmp
directory exists, and if it does, it will print a message saying that the directory exists. If the directory does not exist, it will print a message saying that the directory does not exist.
Keep in mind that the test
command is only one way to check if a directory exists in Linux/Unix shell