CyberKeeda In Social Media

Check for empty strings in Bash




So while writing a script, i was missing out a very important point and that was empty string.

The requirement will be too frequent for every one while writing a script, as everyone needs an input from an user to feed it to run the script, and if by mistake the input remains empty and the script runs smoothly without giving any error leading to cold error within the output configuration file as there is no crosscheck mechanism to verify.

So it is really must to check  and verify that user enters any input or not when asked by script by it's own.

So these two parameters will really help you out.


In Bash you quite often need to check to see if a variable has been set or has a value other than an empty string. This can be done using the -n or -z string comparison operators.
The -n operator checks whether the string is not null. Effectively, this will return true for every case except where the string contains no characters. ie:
car="hello car"
if [ -n $car ]
 
then
      echo "car is not empty"
fi
Similarly, the -z operator checks whether the string is null. ie:
car=""
if [ -z $car ] then
    echo "car is empty"
fi
Note the spaces around the square brackets. Bash will complain if the spaces are not there.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
Designed By Kunal Saha