How can I test if line is empty in shell script?

planetp picture planetp · Apr 5, 2010 · Viewed 81.6k times · Source

I have a shell script like this:

cat file | while read line
do
    # run some commands using $line    
done

Now I need to check if the line contains any non-whitespace character ([\n\t ]), and if not, skip it. How can I do this?

Answer

Arkku picture Arkku · Apr 5, 2010

Since read reads whitespace-delimited fields by default, a line containing only whitespace should result in the empty string being assigned to the variable, so you should be able to skip empty lines with just:

[ -z "$line" ] && continue