My script loops from zero to the CPU count, prints the counter, touches a file, and increments the counter with let. When I run it with sh, most numbers appear twice. What should I check?
Why is my Bash loop printing each number twice?
Answers
First check which shell is actually running the script. Calling sh script.sh bypasses the shebang, and sh may not be Bash. Run it with bash script.sh, or make it executable and run it directly so the shebang selects the interpreter.
That distinction matters here because the script uses Bash-style features, including let. It does not by itself explain the duplicate output, though. Check what sh points to on your system and compare the output when you explicitly use Bash.
Reply to this answer
Add set -x near the start and capture the trace along with the normal output. The trace should show which command runs before each extra number appears. Check whether let resolves to a function, alias, or unexpected command in the shell being used.
The loop shown has only one explicit echo of the counter per iteration, so the duplicate lines need more investigation. The observed output alone does not establish their source.
Reply to this answer
You can simplify the increment to ((counter += 1)) when running under Bash. Shorter variable names would make the loop easier to inspect too. Neither change should be treated as a proven fix for the extra output.
Reply to this answer
Quote the filename expansion in touch, for example touch "core${counter}-temp_orders.csv". The braces make the variable boundary clear and the quotes protect the resulting filename. That is good practice, but the original expansion does not explain the duplicate numbers on its own.
Reply to this answer
One separate issue: after the startup flag becomes true, the outer while true loop keeps spinning without doing useful work. If there is no later work in the full script, remove that loop or exit after setup.
Reply to this answer
Add your answer
Answers are reviewed before publication.
glimmer.26:
If you run it directly, make sure the Bash path in the shebang exists on your system.