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.
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
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
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 || :