相关文章推荐

Programming in Rust has taught me that checking if the variable is empty or not is always a good thing to do, before using the value (or absense of) inside.

To check if a variable is empty, use the -z conditional operator. Following is an example demonstrating this:

if [[ -z "${MY_VAR}" ]]; then
    echo "Empty variable, do not use it"
    echo "Varible is not empty, safe to use it."

You can use the -n test operator to test if a variable is not empty.

To summarize:

Test condition Description

Let's see it in details with examples.

Checking if a variable is empty

Bash has a few conditional expressions, of which you can use one to check if a variable is empty or not. That is the -z operator.

Using the -z operator followed by a variable will result in true if the variable is empty. The condition will evaluate to false if the variable is not empty.

Let's take a look:

#!/usr/bin/env bash
EMPTY_VAR=''
NOT_EMPTY='1000101'
if [[ -z "${EMPTY_VAR}" ]]; then
    echo "Variable 'EMPTY_VAR' is empty"
if [[ ! -z "${NOT_EMPTY}" ]]; then
    echo "Variable 'NOT_EMPTY' is populated"

Here, I have two variables, one of which is empty and the other is populated. I am checking if the empty variable is empty and the non-empty variable is not empty :D

Upon running this script, I get the following output:

Variable 'EMPTY_VAR' is empty
Variable 'NOT_EMPTY' is populated

Checking if a variable is NOT empty

"What do you mean? Didn't you JUST cover it with ! -z? I don't like redundant people!"

I get what you mean, but hear me out. What if I told you that there is a shorter way to check if a variable is not empty than what I demonstrated above. A ! -z already exists: -n.

The -n option, accompanied with a varible, returns true if the variable is not empty.

Let's take a look at the same script, but with just one modification.

#!/usr/bin/env bash
EMPTY_VAR=''
NOT_EMPTY='1000101'
if [[ -z "${EMPTY_VAR}" ]]; then
    echo "Variable 'EMPTY_VAR' is empty"
if [[ -n "${NOT_EMPTY}" ]]; then
    echo "Variable 'NOT_EMPTY' is populated"

The only modification that I have made here is I replaced ! -z with -n. I expect the output to the be the same since the logic--pedantically speaking--is the same.

Here is what I see upon running the modified script:

Variable 'EMPTY_VAR' is empty
Variable 'NOT_EMPTY' is populated

New to Bash? Start here

If you are new to bash scripting, we have a good starting point for you in this Bash tutorial course that covers the essential concepts in the nine chapters.

Bash Scripting Tutorial for Beginners
Get acquainted with bash scripting in this mega tutorial for beginners.

Enjoy bashing bash :)

Bash Tips
Great! Check your inbox and click the link.
Sorry, something went wrong. Please try again.
Navigation

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.

 
推荐文章