Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

sh

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?

like image 244
planetp Avatar asked Apr 05 '10 11:04

planetp


People also ask

How do I check if a string is empty in shell script?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"

What is $? == 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.


3 Answers

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
like image 138
Arkku Avatar answered Oct 19 '22 04:10

Arkku


try this

while read line;
do 

    if [ "$line" != "" ]; then
        # Do something here
    fi

done < $SOURCE_FILE
like image 18
NSC Avatar answered Oct 19 '22 04:10

NSC


bash:

if [[ ! $line =~ [^[:space:]] ]] ; then
  continue
fi

And use done < file instead of cat file | while, unless you know why you'd use the latter.

like image 7
Ignacio Vazquez-Abrams Avatar answered Oct 19 '22 02:10

Ignacio Vazquez-Abrams