Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i compare if my variable holds a newline character in shell Script

I have a script in which I have a line which does put the third line fetched in my variable like this:

variable=`sed -n '3 p' /home/nmsadm/abc.txt`

So variable holds this value Which is in third line of abc.txt. In my case it will be a one word line or an empty/blank line.

How can I compare the variable in a shell script to know if it's an empty/blank line? echo $variable fetched me an empty line.

What is the comparison i need to here so that I am assured it's an empty line? Something like this:

if [ "$variable" = "comparison" ]; then
like image 866
Invictus Avatar asked Oct 15 '25 07:10

Invictus


2 Answers

Empty or undefined:

if [ -z "${variable-}" ]

Single newline:

if [ "${variable-}" = $'\n' ]

Undefined:

if [ "${variable+defined}" != defined ]

Note, the last command is not the opposite of

if [ "${variable-undefined}" = undefined ]

To see why, try running variable=undefined first. "${variable+defined}" has only two possible values: The empty string or defined.

like image 132
l0b0 Avatar answered Oct 17 '25 02:10

l0b0


read str
if [ ${#str} -eq 0 ]       #this can been used to decide whether str is empty or not 
   then
        echo "empty"
else
    echo "not empty"
fi
like image 22
xuqin1019 Avatar answered Oct 17 '25 03:10

xuqin1019