How to determine if a variable is empty in a shell script?

In a Shell script, you can use conditional statements to check if a variable is empty. One common method is to use an if statement along with the test command (or [ ]) to determine if a variable is empty, as shown below:

if [ -z "$var" ]; then
  echo "变量 var 为空"
else
  echo "变量 var 不为空"
fi

In the above code, the -z option is used to check if a variable is empty, $var represents the variable name to be checked. If the variable var is empty, it will output “Variable var is empty”; otherwise, it will output “Variable var is not empty”.

Leave a Reply 0

Your email address will not be published. Required fields are marked *