Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null & empty string comparison in Bash [duplicate]

Tags:

bash

shell

I don't set any values for $pass_tc11; so it is returning null while echoing. How to compare it in if clause?

Here is my code. I don't want "Hi" to be printed...

-bash-3.00$ echo $pass_tc11  -bash-3.00$ if [ "pass_tc11" != "" ]; then > echo "hi" > fi hi -bash-3.00$ 
like image 349
logan Avatar asked Jan 28 '14 13:01

logan


People also ask

What isthe meaning of null?

1 : having no legal or binding force : invalid a null contract. 2 : amounting to nothing : nil the null uselessness of the wireless transmitter that lacks a receiving station— Fred Majdalany. 3 : having no value : insignificant … news as null as nothing …— Emily Dickinson.

What does null mean in text message?

Null usually means "no signal" but don't know in your case as you do not say if you are only getting the notification...and still getting the message?...or not getting the message?...or if it is happening to just one contact?...

What is the synonym of null?

invalid, null and void, void. annulled, nullified, cancelled, abolished, revoked, rescinded, repealed. valid. 2'his curiously null life' lacking in character, empty, characterless, blank, colourless, expressionless, vacuous, insipid, vapid, inane.

What is null in banking?

If your balance on the account page says "null," something has probably gone wrong. To fix this simply force close and re-open the Checkout 51 application.


1 Answers

First of all, note you are not using the variable correctly:

if [ "pass_tc11" != "" ]; then #     ^ #     missing $ 

Anyway, to check if a variable is empty or not you can use -z --> the string is empty:

if [ ! -z "$pass_tc11" ]; then    echo "hi, I am not empty" fi 

or -n --> the length is non-zero:

if [ -n "$pass_tc11" ]; then    echo "hi, I am not empty" fi 

From man test:

-z STRING

the length of STRING is zero

-n STRING

the length of STRING is nonzero

Samples:

$ [ ! -z "$var" ] && echo "yes" $  $ var="" $ [ ! -z "$var" ] && echo "yes" $  $ var="a" $ [ ! -z "$var" ] && echo "yes" yes  $ var="a" $ [ -n "$var" ] && echo "yes" yes 
like image 98
fedorqui 'SO stop harming' Avatar answered Sep 16 '22 15:09

fedorqui 'SO stop harming'