Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find whether or not a variable is empty in Bash?

How can I check if a variable is empty in Bash?

like image 292
Tree Avatar asked Jun 17 '10 11:06

Tree


People also ask

How do you know if a variable is not empty?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.

How do you check a variable in bash?

To check if a variable is set in Bash Scripting, use-v var or-z ${var} as an expression with if command. This checking of whether a variable is already set or not, is helpful when you have multiple script files, and the functionality of a script file depends on the variables set in the previously run scripts, etc.

How check string is empty or not in shell script?

Check if String is Empty using -z String Operator -z string operator checks if given string operand's size is zero. If the string operand is of zero length, then it returns true, or else it returns false. The expression to check if string is empty is [ -z "$s" ] where s is string. String is empty.


2 Answers

In Bash at least the following command tests if $var is empty:

if [[ -z "$var" ]]; then    # Do what you want fi 

The command man test is your friend.

like image 61
Jay Avatar answered Oct 11 '22 03:10

Jay


Presuming Bash:

var=""  if [ -n "$var" ]; then     echo "not empty" else     echo "empty" fi 
like image 25
ChristopheD Avatar answered Oct 11 '22 04:10

ChristopheD