How to check if line from file is empty with bash

I have a while loop that reads lines from a file using a read line. Then I want to check if the string is empty or not, how can I do this? I already found questions about strings with space or about a variable on this site.

+4
source share
2 answers

You can use the test:

[ -z "$line" ] 

On the bash man page:

-z line
True if the string length is zero.

+6
source

The -n statement checks if the string is empty:

 while read line do if [ -n "$line" ] echo $line fi done < file.txt 

If you want to exclude lines containing only white space characters, you can use bash template replacement ${var//find/replacement} . For instance:

 if -n [ "${line//[[:space:]]/}" ] 
+1
source

Source: https://habr.com/ru/post/1383274/


All Articles