Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is If [[-n variable ]] syntax used for in bash

Tags:

bash

shell

I am fixing some old bash scripts I often see

if [[ -n $VARIABLE ]]; then 

syntax I tried to google it but could find why "-n" is used for, following is what I know

Comparisons:
  -eq   equal to
  -ne   not equal to
  -lt   less than
  -le   less than or equal to
  -gt   greater than
  -ge   greater than or equal to

File Operations:

  -s    file exists and is not empty
  -f    file exists and is not a directory
  -d    directory exists
  -x    file is executable
  -w    file is writable
  -r    file is readable

would anyone let me know what -n do ?

like image 379
dpsdce Avatar asked Oct 28 '13 07:10

dpsdce


People also ask

What does [[ ]] mean in bash?

The [[ ... ]] part allows to test a condition using operators. Think of it as an if statement. In your example, you're using the -s operator, which tests that the referenced file is not empty. Copy link CC BY-SA 3.0.

What are [] in bash?

The closing bracket tells test where the expression ends. The double brackets ([[) are a bash built in and can replace the external call to test.

What is if [- Z in bash?

The -z flag is a parameter that checks if the length of a variable is zero and returns true if it is zero. In the example below, the -z flag is used with the test command, and it is tested whether the given string is empty. Bash.

What is IFS variable in bash?

The special shell variable IFS determines how Bash recognizes word boundaries while splitting a sequence of character strings. The default value of IFS is a three-character string comprising a space, tab, and newline: $ echo "$IFS" | cat -et ^I$ $


2 Answers

help test would tell you:

String operators:

  ....

  -n STRING
     STRING      True if string is not empty.
like image 170
devnull Avatar answered Jan 15 '23 14:01

devnull


If $VARIABLE is a string, then [ -n $VARIABLE ] is true if the length of $VARIABLE is non-zero.

Also, [ -n $VARIABLE ] is equivalent with: [ $VARIABLE ], when and only when $VARIABLE is a string.

More about: Introduction to if

like image 25
Radu Rădeanu Avatar answered Jan 15 '23 13:01

Radu Rădeanu