What is the meaning of `! -d` in this Bash command?

Simple question, I don't understand what the ! and -d in the below statement means.

if [ ! -d $directory ]
4

5 Answers

-d is a operator to test if the given directory exists or not.

For example, I am having a only directory called /home/sureshkumar/test/.

The directory variable contains the "/home/sureshkumar/test/"

if [ -d $directory ]

This condition is true only when the directory exists. In our example, the directory exists so this condition is true.

I am changing the directory variable to "/home/a/b/". This directory does not exist.

if [ -d $directory ]

Now this condition is false. If I put the ! in front if the directory does not exist, then the if condition is true. If the directory does exists then the if [ ! -d $directory ] condition is false.

The operation of the ! operator is if the condition is true, then it says the condition is false. If the condition is false then it says the condition is true. This is the work of ! operator.

if [ ! -d $directory ]

This condition true only if the $directory does not exist. If the directory exists, it returns false.

1

The brackets are the test executable, the exclamation mark is a negation, and the -d option checks whether the variable $directory is a directory.

From man test:

-d FILE FILE exists and is a directory
! EXPRESSION EXPRESSION is false

The result is an if statement saying "if $directory is not a directory"

1

! means not

-d means test if directory exists

So, if [ ! -d $directory ] means if $directory does not exist, or $directory isn't a directory (maybe a file instead).

Usually this is followed by a statement to create the directory, such as

if [ ! -d $directory ]; then mkdir $directory
fi
2

-d is a test operator in bash and when you put ! before test operator - its negating the same

0
  • ! negates the condition.
  • -d option checks $directory is a directory or not.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like