乐闻世界logo
搜索文章和话题

How do you check if a string is empty in shell scripting?

1个答案

1

A common way to check if a string is empty in shell scripts is to use the -z test operator. This operator checks if the string is empty. If the string is empty, the condition evaluates to true.

Here is a basic example script demonstrating how to use the -z operator to check if a string is empty:

bash
#!/bin/bash # Define a string variable str="" # Use -z to test if the string is empty if [ -z "$str" ]; then echo "String is empty" else echo "String is not empty" fi

In this script, the variable str is defined and initialized as an empty string. The [ -z "$str" ] condition in the if statement checks if str is empty. Since str is empty, the output will be "String is empty".

Alternatively, you can implement the check for non-empty strings using the -n test operator or directly using the variable itself as a condition (in shell, a non-empty string evaluates to true):

bash
#!/bin/bash # Define a string variable str="" # Use -n to test if the string is non-empty if [ -n "$str" ]; then echo "String is not empty" else echo "String is empty" fi # Or directly use the variable as a condition if [ "$str" ]; then echo "String is not empty" else echo "String is empty" fi

The second and third methods in these scripts are also effective ways to check if a string is empty. When writing scripts, you can choose the most suitable detection method based on specific requirements.

2024年8月14日 17:30 回复

你的答案