计数器变量未更新

时间:2015-04-28 12:55:06

标签: bash while-loop

我正在尝试编写一个脚本来自动从一个回购中拉取,渲染和推送一个LaTeX文档。拉/推没有问题,但是为了开始渲染,我想检查自上次更新以来.tex文件是否已更改(变量oldHash保存信息)。问题是当我执行代码时,一旦循环退出,计数器变量就会重置为0。这是代码:

#!/bin/bash

##### PULL FROM THE REPO AND SAVE THE HASH #####

# Get the diff between the two commits
diffFiles=$(git diff --name-only "$oldHash" HEAD@{0})

# The commmand produces the following output:
# Chapters/Chapter6.tex
# Other/CustomEnvironments.tex
# RawMaterial/LinearAlgebraNotes_4.pdf
# buildAll.sh
# main.tex

numberOfTexFiles=0

# Loop through every line of the output and strip the files from their extension
printf %s "$diffFiles" | while IFS= read -r line
do
    baseName=$(basename "$line")
    extension="${baseName##*.}"
    if [[ "$extension" == 'tex' ]]; then
        # If the file is a Tex, update the counter
        numberOfTexFiles=$(($numberOfTexFiles+1))
        echo $numberOfTexFiles
    fi
done

echo $numberOfTexFiles

if [ $numberOfTexFiles -gt 0 ]; then
    echo "FILES HAVE CHANGED"
    # Run some other stuff (namely pdflatex)
else
    echo "NOTHING CHANGED"
fi

现在发生的是最后一个if语句求值为false,并且永远不会调用pdflatex命令。我该如何解决?

修改

正如JID所建议的那样,重定向就是我所需要的。这是我的解决方案:

while IFS= read -r line
do
    baseName=$(basename "$line")
    extension="${baseName##*.}"
    if [[ "$extension" == 'tex' ]]; then
        # If the file is a Tex, update the counter
        numberOfTexFiles=$(($numberOfTexFiles+1))
        echo $numberOfTexFiles
    fi
done <<< $(printf %s "$diffFiles")

1 个答案:

答案 0 :(得分:-1)

if [[ "$extension" == 'tex' ]]; 

如果可能导致此问题,我的猜测是分号。你能否删除它,看看它是否有效?