Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to supress errors for missing file in while loop

Tags:

bash

For example, here's part of my bash script:

while read line
do
    [some stuff]
done < $group.$project.$branch.notready.txt

But, during the course of the loop, whether this one or whether this loop is within another loop, the name of the file can change from notready to ready. When that happens, I get no such file or directory error. It's fine if the file is not there for the sake of the script, but is there a way to suppress the error?

I've tried:

while read line 2>/dev/null

but that don't work.

Edit: this may be an easier way to replicate

while read line
do
    echo "$line"
done < random.file.dont.exist.txt
like image 465
Gene Avatar asked Apr 19 '26 11:04

Gene


1 Answers

If you wrap the whole while statement in braces it works, but note that this will supress any error messages from any part of the loop:

{
    while read line; do
        echo "$line"
    done < random.file.dont.exist.txt
} 2>/dev/null
like image 191
wjandrea Avatar answered Apr 21 '26 03:04

wjandrea