我有一个代码,我想从文件中安装apt软件包,并记录结果。
如果成功,我想打印“
我已经用伪造的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
###############################
答案 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