Bash在循环中检测错误然后继续处理

时间:2014-10-31 16:41:40

标签: bash

我想处理文本文件中包含的Homebrew公式列表。如果存在安装错误(例如已安装,错误的公式名称),我希望它写入错误,但继续处理。 Github project

到目前为止我所拥有的:

...
# 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
...

我该怎么做?

2 个答案:

答案 0 :(得分:5)

有帮助吗?

...
# 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
...

请注意,如果公式包含空格,则for循环将拆分该行。写一下可能更好:

...
# 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"
...

答案 1 :(得分:1)

这应该很简单。

# 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

向安装部件添加if语句将检查brew的退出状态,如果失败,则会报告错误并继续。