Check if a directory exists in Linux or Unix shell

You can use the test command or the [ command with the -d option to check if a directory exists in a Linux or Unix shell. Here are some examples:

  • test -d /path/to/directory or [ -d /path/to/directory ]
  • if [ -d /path/to/directory ]; then echo "Directory exists"; else echo "Directory does not exist"; fi

You can also use the ls command with the -d option to check if a directory exists, and redirect stderr to /dev/null to avoid error messages. For example:

  • ls -d /path/to/directory 2>/dev/null

You can also use the find command to search for the directory and check if it exists:

find /path -type d -name 'directory_name'

This will return the path to the directory if it exists, or nothing if it does not.

You can also use the stat command to check if a directory exists, for example:

stat --printf=%F /path/to/directory

This will return the type of file, including “directory” if the directory exists, and an error message if it does not.

Leave a Comment