I have a bash script repeat loop that checks for a variable in a folder of file names and then echoes an error message for each file it finds, after which it echoes an ongoing file count for the ones it successfully processes.
Here is the relevant code:
if [[ $myVar = 1 ]]; then
echo "ERROR: $myFilename"
((count++))
echo -en "Total Files: $count \r"
fi
The objective is to insert a blank line between the last error message it displays and the total file count, like this:
ERROR: testfile1
ERROR: testfile2
ERROR: testfile3
Total File Count: 3
The problem I am having is, without adding an echo "" after the error message, it looks like this:
if [[ $myVar = 1 ]]; then
echo "ERROR: $myFilename"
echo""
((count++))
echo -en "Total Files: $count \r"
fi
ERROR: testfile1
ERROR: testfile2
ERROR: testfile3
Total File Count: 3
But if I add an echo "" after the error message, it adds the blank like to each cycle of error checking so it looks like this:
if [[ $myVar = 1 ]]; then
echo "ERROR: $myFilename"
echo""
((count++))
echo -en "Total Files: $count \r"
ERROR: testfile1
ERROR: testfile2
ERROR: testfile3
Total File Count: 3
My question is, how can I add that blank line to the code (either in this section or after) so that the [echo ""] is only applied at the end? Is there a special condition in Bash that would allow me to run a command only once within the repeat loop?
I need the counter to remain inside the loop so it increments the number after each cycle, but I also want to insert a blank line between them.
$'\r'only does what you want when the cursor is on the same line you want to overwrite. When you have other lines printed, you're overwriting the line the cursor is now on, not the line it was on when you last printed your message.ERROR: $myFilenamemessage, such that you want to suppress that message? That's an easy enough problem.echo -enis really best avoided;printf '\r%s' "message here"is much more reliable, in that it'll work the same way across different bash configurations [and non-bash shells], different operating systems, etc. more reliably)