使用&&和||组合不起作用

时间:2019-06-07 10:59:36

标签: bash

我有一个代码,我想从文件中安装apt软件包,并记录结果。

如果成功,我想打印“ install:成功”,如果失败,我需要写“ install:failed”并增加一个名为failed的变量

我已经用伪造的apt软件包名称填充了reqruiments.apt,以使其失败。

LOGFILE=log.txt
FAILED=0
for req in $(cat requirements.apt)
    do
        apt install -y "$req" &> aptInstall.log &&
        printf "$req: Succes\n" >> $LOGFILE ||
        (printf "$req: Failed\n" >> $LOGFILE && ((FAILED++)))
    done
        printf "\n\nApt install ran with $FAILED failed packages\n"  >> $LOGFILE
        printf "###############################\n" >> $LOGFILE
        printf "\n\n" >> $LOGFILE

我的日志如下:

python-opencv-tre: Failed
build-essential-tre: Failed
python-scipy-tre: Failed


Apt install ran with 0 failed packages
###############################

我会期望的

python-opencv-tre: Failed
build-essential-tre: Failed
python-scipy-tre: Failed


Apt install ran with 3 failed packages
###############################

1 个答案:

答案 0 :(得分:4)

问题是您的FAILED增量在另一个shell中运行。当您运行

(printf "$req: Failed\n" >> $LOGFILE && ((FAILED++)))

您产生了一个新的过程;在该过程中,FAILED会增加,但在您的“主”过程中不会。您应该删除那些括号。

printf "$req: Failed\n" >> $LOGFILE && ((FAILED++))

注意:假设您希望将命令分组在一起而不产生新进程;考虑使用花括号:

{ printf "$req: Failed\n" >> $LOGFILE && ((FAILED++)) ; }

向您展示此示例:

FAILED=0
for i in $(seq 1 3); do
    (echo "FAILED=$FAILED" && ((FAILED++)))
done

给予

FAILED=0
FAILED=0
FAILED=0

现在除去周围的括号:

FAILED=0
for i in $(seq 1 3); do
    echo "FAILED=$FAILED" && ((FAILED++))
done

你会得到

FAILED=0
FAILED=1
FAILED=2