Shell脚本中printf输出Maven依赖处理信息重复问题求助
Hey there! Let's sort out why your printf progress messages are showing duplicated/truncated content like Writing dependencies in ../path/all_dependencies.txt -- Applying with "mvn dependency:tree -Dverbose "..... -- Applying with "mvn dependency:t....
The Root Cause
This happens because when you update progress text without properly clearing the existing line, shorter subsequent outputs leave leftover characters from the longer previous line visible. For example, if you first print a long mvn command and then a shorter version (or the terminal wraps/updates before clearing), the old characters don't get overwritten.
The Fix: Proper Line Clearing & Cursor Positioning
Use ANSI escape sequences to clear the current line before printing new progress text, and send a carriage return (\r) to move the cursor back to the start of the line (instead of a newline \n which would create a new line each time).
Here's how to adjust your printf statement:
# Clear the line from cursor to end, print progress, then return to line start printf "\033[KWriting dependencies in %s -- Applying with \"%s\".....\r" "../path/all_dependencies.txt" "mvn dependency:tree -Dverbose"
Breakdown of the escape sequences:
\033[K: This ANSI escape code clears all characters from the current cursor position to the end of the line. Ensures no leftover text from previous prints remains.\r: Carriage return moves the cursor back to the start of the current line, so the next printf will overwrite the existing content instead of creating a new line.
Handling Non-Terminal Environments
If your script might run in a non-interactive environment (like being redirected to a log file), the ANSI escape sequences will show up as raw characters. To avoid this, check if you're running in a terminal first:
# Detect if we're in an interactive terminal if [ -t 1 ]; then CLEAR_LINE="\033[K" else CLEAR_LINE="" fi # Use the clear sequence only if in a terminal printf "%sWriting dependencies in %s -- Applying with \"%s\".....\r" "$CLEAR_LINE" "$OUTPUT_FILE" "$MVN_CMD"
Final Touch: Finish with a Newline
Once your Maven command completes, print a newline to "lock in" the final progress message so it doesn't get overwritten by subsequent output:
# After the mvn command finishes printf "\033[KDone writing dependencies to %s\n" "$OUTPUT_FILE"
That should eliminate the duplicated/truncated progress text entirely!
内容的提问来源于stack exchange,提问作者Evgeny Ignatik

