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

cra*_*aig 1 bash

我想处理一个包含在文本文件中的Homebrew公式列表.如果有安装错误(例如已经安装,错误的公式名称),我希望它写错误,但继续处理.在Github上项目.

到目前为止我所拥有的:

...
# 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
...
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

Kan*_*han 6

那应该很简单。

# 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
Run Code Online (Sandbox Code Playgroud)

在安装部分添加一条if语句将检查退出状态brew,如果失败则报告错误并继续。


Edo*_*iel 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
...
Run Code Online (Sandbox Code Playgroud)

请注意,如果公式包含空格,则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"
...
Run Code Online (Sandbox Code Playgroud)