What is the meaning of `! -d` in this Bash command?
-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.
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"