Languages
[Edit]
EN

Bash - check if string is not empty

0 points
Created by:
Zeeshan-Peel
850

In this article, we would like to show you how to check if string is not empty in Bash.

Practical example

In this example, we use -n operator to check if string length is not zero inside the if statement.

script.sh file:

#!/bin/bash

string="example text..."

if [ -n "$string" ]; then
    echo "The string is not empty"
fi

Note: this approach should be used in POSIX shells where other solutions may not work.

Run in command line:

./script.sh

Output:

The string length is not empty

 

Altermative notation

1. test based solution

#!/bin/bash

string="example text..."

if test -n "$string"; then
    echo "The string is not empty"
fi

Note: [ ] notation is shorthand of test command.

2. [[ ]] based solution

#!/bin/bash

string="example text..."

if [[ -n "$string" ]]; then
    echo "The string is not empty"
fi

Note: [[ ]] notation is like extended test command, adding additional features (e.g. regular expressions).

 

See also

  1. Bash - check if string is empty

Alternative titles

  1. Bash - check if string is not null
  2. Bash - check if string length is not zero
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join