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

求助:使用entr触发Bash脚本时,>>追加重定向导致输出重复写入

Java编译运行脚本重复输出问题

脚本功能

  • 编译指定Java文件,运行程序时从io/in.txt读取输入,输出写入io/out.txt
  • 可通过配置项_R_CAN_APPEND_OUTPUT选择输出文件的覆盖(>)或追加(>>)模式

监听触发命令

使用entr工具监听Main.java和io/in.txt文件变化,触发脚本执行:

command ls Main.java io/in.txt | entr -d ./run.sh Main.java

异常现象

当启用追加重定向(_R_CAN_APPEND_OUTPUT=true)时,每次文件发生变化,控制台仅打印一次"execution successful"日志,但io/out.txt中的内容被重复写入两次,实际脚本执行了两次输出写入操作。该问题出现在macOS系统的VSCode环境中。

脚本代码

# ----------- 配置项 --------------
_R_JAVA_HOME="/opt/homebrew/Cellar/openjdk/23.0.2/libexec/openjdk.jdk/Contents/Home"
_R_IO_DIR="io"
_R_BIN_DIR=".bin"
_R_ENABLE_ASSERTIONS=true
_R_CAN_APPEND_OUTPUT=true
_R_SILENT_MODE=false
# ------------ 用户配置 --------------
# 检查run.conf是否存在并加载
# 用户可通过该文件覆盖默认设置
[ -f run.conf ] && source run.conf
# ----------------------------------------

# -------------- 颜色定义 ------------------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
RESET='\033[0m'

print_msg() {
    local color=$1; shift
    local msg=$1
    if [ "$_R_SILENT_MODE" = true ]; then
        return
    fi
    echo -e "${!color}${msg}${RESET}"
}

print_error()   { print_msg RED "fatal: $1"; }
print_success() { print_msg GREEN "$1"; }
print_warning() { print_msg YELLOW "warning: $1"; }
print_info()    { print_msg BLUE "$1"; }
# ----------------------------------------

# 检查 :: 使用方法
if [ -z "$1" ]; then
    print_info "usage: $0 <javafile>"
    exit 1
fi

# 步骤 :: 解析输入
java_file="$1"
class_name=$(basename "$java_file" .java)

# 方法 :: 编译  
compile_java_file() {
    ${_R_JAVA_HOME}/bin/javac -d "$_R_BIN_DIR" "$java_file"
    return $?
}

# 方法 :: 运行 
run_java_program() {
    local cmd="${_R_JAVA_HOME}/bin/java"
    [ "$_R_ENABLE_ASSERTIONS" = true ] && cmd="$cmd -ea"
    cmd="$cmd -cp $_R_BIN_DIR $class_name"

    local input_file="$_R_IO_DIR/in.txt"
    local output_file="$_R_IO_DIR/out.txt"
    local redirection=">"

    [ "$_R_CAN_APPEND_OUTPUT" = true ] && redirection=">>"

    eval "$cmd < \"$input_file\" $redirection \"$output_file\""
    return $?
}

# 步骤 :: 编译 
compile_java_file
if [ $? -ne 0 ]; then
    print_error "compilation failed."
    exit 1
fi

# 步骤 :: 运行
run_java_program
if [ $? -ne 0 ]; then
    print_error "execution failed."
    exit 1
else 
    print_success "execution successful."
    # print_info "Output written to: $_R_IO_DIR/out.txt"
fi

内容的提问来源于stack exchange,提问作者infi null

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 00:07:02