You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shell脚本中printf输出Maven依赖处理信息重复问题求助

Fixing Duplicated Progress Output in Your Maven Dependency Extraction Shell Script

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:12:19