0

I have code like this:

#!/bin/bash

n=0
for file in *.txt
do
        tail -c1 $file | read -r _ || (
                ((n++))
                echo "$file is missing a final newline, issue #$n"
        )
done

But when I run it, the numbers aren't incrementing:

a.txt is missing a final newline, issue #1

b.txt is missing a final newline, issue #1

How can I fix this? It looks like a scope issue, since the 0 is incremented to 1 as though the previous increment was ignored.

2
  • 1
    Not related to your question, but the code will fail if a filename contains whitespace, using double-quotes is much safer: tail -c1 "$file". Commented May 10, 2016 at 19:40
  • @cdarke: Good point! In my actual use case I'm using a more specific glob which doesn't permit spaces, but that should be useful for future visitors to this question. :) Commented May 10, 2016 at 20:01

1 Answer 1

1

your commands embedded between parentheses runs as a subshell, each subshell in the loop starts over with the value of n set at the parent level (n=0).

Just change the parenthesis to curly braces (a terminal semicolon or newline is required).

Sign up to request clarification or add additional context in comments.

2 Comments

That's it! Such a simple thing to miss, thanks for spotting it.
Or just use a single command: `... || echo "$file is missing a final newline, issue #$((++n))"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.