What does the [[ -z "$PORT" ]] && export PORT=8080 bash command do?

Viewed 172

I am following a tutorial and they use the command [[ -z "$PORT" ]] && export PORT=8080 and I don't fully understand what it's doing. My knowledge of bash commands is very basic and so I am not even sure what to google to figure this out.

The little knowledge I have suggests to me that this somehow checks if the env variable PORT is set and if not set it to 8080. However, I don't actually understand what is going on, except for the last part, export PORT=8080.

Could anyone explain what the different operations are doing here?

3 Answers

Here is what is going on -

  • [[ -z "$PORT" ]] is checking whether the length of the string in variable "$PORT" is zero or Not.
  • the second part of && is only evaluated if the first part is true.

So short answer is this -

if the length of the string "$PORT" is zero then it will export a variable named PORT which will have the value of 8080 otherwise it will not export the variable and will moved on to the next statement in bash script.

Using && there is taking advantage of it being a "short-circuiting" operator. It tests the first command, and only executes the second command if it fails.

So this is a short-hand way of writing

if [[ -z "$PORT" ]]
then
    export PORT=8080
fi

Which means if $PORT is unset or empty, it's set to 8080 and exported.

First, let's clarify that the first command is an expression:

enter image description here

Try this:

echo $foo

it will yield empty string. Now, if you execute

[[ -z "$PORT" ]] && export PORT=8080

and then run

echo $foo

then the result is 8080.

Explanation:

  • -z string is true if string is empty and false otherwise
  • the right side of && is evaluated if and only if the left-hand side is true, otherwise the logical expression is evaluated as false
  • the right-hand-side does an export

In short: $PORT is defaulted to 8080.

Related