Search code examples
linuxstringbashif-statementcomparison

Test if string has non whitespace characters in Bash


My script is reading and displaying id3 tags. I am trying to get it to echo unknown if the field is blank but every if statement I try will not work. The id3 tags are a fixed size so they are never null but if there is no value they are filled with white space. I.E the title tag is 30 characters in length. Thus far I have tried

echo :$string: #outputs spaces between the 2 ::

if [ -z "$string" ] #because of white space will always evaluate to true

x=echo $string | tr -d ' '; if [ -z "$string" ]; #still evaluates to true but echos :$x: it echos ::

the script

#!bin/bash
echo "$# files";
while [ "$i" != "" ];
do
   TAG=`tail -c 128 "$i" | head -c 3`;
   if [ $TAG="TAG" ]
   then
      ID3[0]=`tail -c 125 "$1" | head -c 30`;
      ID3[1]=`tail -c 95 "$1" | head -c 30`;
      ID3[2]=`tail -c 65 "$1" | head -c 30`;
      ID3[3]=`tail -c 35 "$1" | head 4`;
      ID3[4]=`tail -c 31 "$i" | head -c 28`;
      for i in "${ID3[@]}"
      do
         if [ "$(echo $i)" ] #the if statement mentioned
         then
            echo "N/A";
         else
            echo ":$i:";
         fi
      done
   else
      echo "$i does not have a proper id3 tag";
   fi
   shift;
done

Solution

  • You can use bash's regex syntax.

    It requires that you use double square brackets [[ ... ]], (more versatile, in general).
    The variable does not need to be quoted. The regex itself must not be quoted

    for str in "         "  "abc      " "" ;do
        if [[ $str =~ ^\ +$ ]] ;then 
          echo -e "Has length, and contain only whitespace  \"$str\"" 
        else 
          echo -e "Is either null or contain non-whitespace \"$str\" "
        fi
    done
    

    Output

    Has length, and contain only whitespace  "         "
    Is either null or contain non-whitespace "abc      " 
    Is either null or contain non-whitespace ""