Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How to check if a directory is a directory in bash?


Asked by Weston Welch on Dec 02, 2021 FAQ



This code will loop through all files in the current directory, check if f is a directory, then echo f if the condition returns true. If f is equal to */, echo $f will not execute. Use shopt -u dotglob to exclude hidden directories (or setopt dotglob / unsetopt dotglob in zsh). You can use pure bash for that, but it's better to use find:
Besides,
This command checks for the directory /tmp/test. If it exists, the system displays File exists. You can now use bash to check if a file and directory exist. You can also create simple test scripts as you now understand the functions of a basic bash script file.
Furthermore, #!/bin/bash # function to check if passed argument is a directory and exists checkIfDirectory () { # $1 meaning first argument if [ -d "$1" ]; then echo "$1 exists and is a directory." else echo "$1 is not a directory."
Indeed,
Make sure you always wrap shell variables such as $DIR in double quotes ( "$DIR" to avoid any surprises in your shell scripts: One can use the test command to check file types and compare values. For example, see if FILE exists and is a directory.
Consequently,
You can use ! to check if a directory does not exists on Unix: [ ! -d "/dir1/" ] && echo "Directory /dir1/ DOES NOT exists." One can check if a directory exists in Linux script as follows: DIR = "/etc/httpd/" if [ -d "$DIR" ]; then # Take action if $DIR exists. # echo "Installing config files in $ {DIR}..."