Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

People also ask

What does [- Z $1 mean in Bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What does ${} mean in Bash?

${} Parameter Substitution/Expansion A parameter, in Bash, is an entity that is used to store values. A parameter can be referenced by a number, a name, or by a special symbol.

What is $_ in Bash?

The “$_” special variable can even be used for displaying the path of a Bash script in Ubuntu 20.04. It can do so if you create a simple Bash script and use the “$_” special variable before writing any other command in your Bash script. By doing so, you will be able to get the path of your Bash script very easily.


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


! 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

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

http://www.techtrunch.com/2011/11/25/test-operators-bash/


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