In bash, what is the difference between a null string and an empty string?

Asked

Viewed 295 times

4

I wonder if there is a difference in how bash represents variables with null values

var=

and with empty strings

var=""

What care should I take when manipulating variables like these?

2 answers

3

Consider the following:

var1=

var2=""

The variable var1 has no value, has its null value (null). A null value is exactly a "NOTHING"! Different from the variable value var2 that has an empty string.

Imagine that we will be using some object language (just to be more didactic). Using the Python example:

$ python
Python 2.7.12 (default, Jun 29 2016, 14:05:02) 
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> var1 = None
>>> var2 = ""
>>> type(var1)
<type 'NoneType'>
>>> type(var2)
<type 'str'>

ps: None in python is the same thing as null in other languages.

The situation of var1 demonstrates that the variable does not initialize a value. Therefore, a "nothing" cannot receive any feedback if you try... you will receive the famous error NullPointerException because the "nothing" cannot receive attribute(s): it does not receive values and points to anything.

>>> len(var1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'NoneType' has no len()

To var2 is a variable of the type string empty. Something "empty" has its value of zero because this way the variable is initialized. That is, even if it is a "blank character" it has its reserved place in memory. So, when used the len() (length) will be returned 0:

>>> len(var2)
0

0

Please consider the shell script in sh:

#! /bin/sh 

aNullString=
anEmptyString=""

if [ -z ${aNullString} ] ; then
    echo The string aNullString is empty 
else
    echo The string aNullString is not empty 
fi

if [ -z ${anEmptyString} ] ; then
    echo The string anEmptyString is empty 
else
    echo The string anEmptyString is not empty 
fi

if [ ${aNullString} = ${anEmptyString}] ; then
    echo The strings aNullString and anEmptyString are equal
else
    echo The strings aNullString and anEmptyString differ 
fi

He suggests that a= and b='' are the same character string as its result is:

The string aNullString is empty
The string anEmptyString is empty
The strings aNullString and anEmptyString are equal

Browser other questions tagged

You are not signed in. Login or sign up in order to post.