Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does [ -n "$VARIABLE" ] || exit 0 mean

Tags:

bash

shell

Looking at correcting an issue in /etc/init.d/hostapd on Debian. However, I have no clue what this line of code does nor how it works

[ -n "$DAEMON_CONF" ] || exit 0

In searching online for bash tutorials, I've never seen anyone do this

When I run the code, my shell window closes (because $DAEMON_CONF is not set to anything). If I change the code to

[ -n "not empty" ] || exit 0

my console window does not close.

so, -n evaluates to true, and or'ed with exit 0, is what?

like image 622
Kearney Taaffe Avatar asked Jul 05 '16 20:07

Kearney Taaffe


People also ask

What does exit 0 Do in shell script?

Exit Status Each shell command returns an exit code when it terminates, either successfully or unsuccessfully. By convention, an exit code of zero indicates that the command completed successfully, and non-zero means that an error was encountered.

What is exit code 0 bash?

For the bash shell's purposes, a command which exits with a zero (0) exit status has succeeded. A non-zero (1-255) exit status indicates failure. If a command is not found, the child process created to execute it returns a status of 127.

What is exit in shell script?

exit exits the calling shell or shell script with the exit status specified by n . If you omit n , the exit status is that of the last command executed (an end-of-file exits the shell). return exits a function with the return value specified by n . If you omit n , the return status is that of the last command executed.

What does if variable mean in PHP?

It checks whether $variable evaluates to true . There are a couple of normal values that evaluate to true , see the PHP type comparison tables. if ( ) can contain any expression that ultimately evaluates to true or false .


2 Answers

If the expression in [] returns false, do the thing after the or || (and exit 0). Otherwise, it will short circuit and the next statement will be evaluated.

like image 198
Elliott Frisch Avatar answered Oct 01 '22 02:10

Elliott Frisch


[ is and alternate name for the command test. You can learn about the parameters/flags whatnot by looking at test's manpage:

man test

You'll see for -n:

-n STRING

          the length of STRING is nonzero

Furthemore || means OR. So if the test command returns False then the stuff after the || will be executed. If test returns true, then it won't be executed.

Written out your command says: "If the variable $DAEMON_CONF lacks a value, then exit with return code 0"

The longhand version would be something like:

if test ! -n "$DAEMON_CONF"; then
    exit 0
fi
like image 27
JNevill Avatar answered Oct 01 '22 02:10

JNevill