Why doesn't my variable seem to increment in my bash while loop?

前端 未结 3 1354
自闭症患者
自闭症患者 2020-12-15 07:47

I am fairly new to bash scripting. I can\'t seem to get the correct value of my counting variables to display at the end of of a while loop in my bash script.

相关标签:
3条回答
  • 2020-12-15 07:57

    This is because you are using the useless cat command with a pipe, causing a subshell to be created. Try it without the cat:

    while read filename ; do
        N=$((N+1))
        ....
    done < file
    
    0 讨论(0)
  • 2020-12-15 08:20

    Alternatively, if you want to keep the cat for some reason, you can fix your script simply by adding this line before the cat instruction:

    shopt -s lastpipe 
    
    0 讨论(0)
  • 2020-12-15 08:22

    More generally, sometimes you want to pipe the output of a command. Here's an example that uses process substitution to lint JavaScript files about to be committed by Git and counts the number of files that failed:

    # $@ glob
    git-staged-files() {
      git diff --cached -C -C -z --name-only --relative --diff-filter=ACMRTUXB "$@"
    }
    
    # $@ name
    map() { IFS= read -rd $'\0' "$@"; }
    
    declare -i errs=0
    while map file; do
      echo "Checking $file..."
      git show ":$file"|
      eslint --stdin --stdin-filename "$file" || ((++errs))
    done < <(git-staged-files \*.js)
    
    ((errs)) && echo -en "\e[31m$errs files with errors.\e[00m " >&2 || :
    
    0 讨论(0)
提交回复
热议问题