Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash detect an error in loop then continue processing

Tags:

bash

I would like to process a list of Homebrew formulas contained in a text file. If there is an installation error (e.g. already install, bad formula name), I'd like it to write the error, but continue processing. The Github project.

What I have so far:

...
# process list of formulas that have been installed
for i in $(cat $FILE) ; do

    echo "Installing $i ..."

    # attempt to install formula; if error write error, process next formula

    brew install $i

done
...

How do I do this?

like image 926
craig Avatar asked Mar 06 '26 04:03

craig


2 Answers

Does it help?

...
# process list of formulas that have been installed
for i in $(< "$FILE") ; do

    echo "Installing $i ..."

    # attempt to install formula; if error write error, process next formula

    brew install "$i" || continue

done
...

Note that if formula contains blanks then the for loop will split the line. It might be better to write:

...
# process list of formulas that have been installed
while read i ;  do

    # Jump blank lines
    test -z "$i" && continue

    echo "Installing $i ..."

    # attempt to install formula; if error write error, process next formula

    brew install "$i" || continue

done < "$FILE"
...
like image 191
Edouard Thiel Avatar answered Mar 08 '26 16:03

Edouard Thiel


That should be simple.

# process list of formulas that have been installed
for i in $(<"$FILE") ; do

    echo "Installing $i ..."

    # attempt to install formula; if error write error, process next formula

    if ! brew install $i
    then
        echo "Failed to install $i"
        continue
    fi

done

Adding an if statement to the installation part will check for the exit status of brew and if it failed then will report and error and continue.

like image 35
Kannan Mohan Avatar answered Mar 08 '26 16:03

Kannan Mohan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!