Pullingmyhairout Pullingmyhairout - 2 years ago 101
Linux Question

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

Simple question, I don't understand what the

in the below statement means.

if [ ! -d $directory ]

Answer Source

-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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download