Check if the string is neither empty nor space in shell script

I am trying to run the following shell script, which should check if the line is neither a space nor empty. However, I get the same result for all three lines mentioned. I tried using the syntax "[[", but to no avail.

Here is my code:

str="Hello World" str2=" " str3="" if [ ! -z "$str" -a "$str"!=" " ]; then echo "Str is not null or space" fi if [ ! -z "$str2" -a "$str2"!=" " ]; then echo "Str2 is not null or space" fi if [ ! -z "$str3" -a "$str3"!=" " ]; then echo "Str3 is not null or space" fi 

I get the following output:

 # ./checkCond.sh Str is not null or space Str2 is not null or space 
+44
bash shell freebsd
Nov 22 '12 at 9:30
source share
6 answers

You need a seat on either side of != . Change your code to:

 str="Hello World" str2=" " str3="" if [ ! -z "$str" -a "$str" != " " ]; then echo "Str is not null or space" fi if [ ! -z "$str2" -a "$str2" != " " ]; then echo "Str2 is not null or space" fi if [ ! -z "$str3" -a "$str3" != " " ]; then echo "Str3 is not null or space" fi 
+75
Nov 22 '12 at 9:40
source share

To check an empty string in a shell

 if [ "$str" == "" ];then echo NULL fi 

OR

 if [ ! "$str" ];then echo NULL fi 
+39
Nov 22 '12 at 9:37
source share

If you need to check any number of spaces, and not just one space, you can do this:

To cut a line of extra space (also smooths spaces in the middle and one space):

 trimmed=`echo -- $original` 

-- ensures that if $original contains switches that are echoed, they will still be considered normal arguments that will be echoed. It is also important not to place "" around $original , or spaces are not removed.

After that, you can simply check if $trimmed .

 [ -z "$trimmed" ] && echo "empty!" 
+11
Nov 22 '12 at 9:43
source share

To check if a string is empty or contains only spaces that you could use:

 shopt -s extglob # more powerful pattern matching if [ -n "${str##+([[:space:]])}" ]; then echo '$str is not null or space' fi 

See Enhancing Shell Settings and Pattern Matching in the Bash Guide.

+6
Nov 22 '12 at 9:41
source share

Another quick test so that the string has something in it, but space.

 if [[ ! -z "${str/ //}" ]]; then echo "It is not empty!" fi 
+2
May 23 '16 at 18:36
source share
 [ $(echo $variable_to_test | sed s/\n// | sed s/\ //) == "" ] && echo "String is empty" 

Removing all lines and spaces from a line will result in the empty line being reduced to zero, which can be tested and acted upon

+1
May 01 '17 at 11:40
source share



All Articles