Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a directory exists in a Bash shell script?

What command can be used to check if a directory exists or not, within a Bash shell script?

like image 458
Grundlefleck Avatar asked Sep 12 '08 20:09

Grundlefleck


People also ask

How do I check a directory?

Use the ls command to display the contents of a directory. The ls command writes to standard output the contents of each specified Directory or the name of each specified File, along with any other information you ask for with the flags.

How do I find the bash script directory?

You can use $BASH_SOURCE : #!/usr/bin/env bash scriptdir="$( dirname -- "$BASH_SOURCE"; )"; Note that you need to use #!/bin/bash and not #!/bin/sh since it's a Bash extension.


1 Answers

To check if a directory exists in a shell script, you can use the following:

if [ -d "$DIRECTORY" ]; then   # Control will enter here if $DIRECTORY exists. fi 

Or to check if a directory doesn't exist:

if [ ! -d "$DIRECTORY" ]; then   # Control will enter here if $DIRECTORY doesn't exist. fi 

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:

ln -s "$ACTUAL_DIR" "$SYMLINK" if [ -d "$SYMLINK" ]; then    rmdir "$SYMLINK"  fi 

Will produce the error message:

rmdir: failed to remove `symlink': Not a directory 

So symbolic links may have to be treated differently, if subsequent commands expect directories:

if [ -d "$LINK_OR_DIR" ]; then    if [ -L "$LINK_OR_DIR" ]; then     # It is a symlink!     # Symbolic link specific commands go here.     rm "$LINK_OR_DIR"   else     # It's a directory!     # Directory command goes here.     rmdir "$LINK_OR_DIR"   fi fi 

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.

like image 101
Grundlefleck Avatar answered Sep 30 '22 01:09

Grundlefleck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!