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

求助Unix专家:script工具使用困境及特定日志生成需求

解决Unix下模拟逐行执行命令并生成指定内容日志的问题

Hey there! Let's tackle this problem you're having with the script utility—it sounds like it's not quite fitting your use case, and I totally get why searching for help can be tricky when "script" is such an overloaded term in Unix land.

From your description, you want to take an input file (like testscript.scr), run each line as a command one-by-one (waiting for each to finish before moving on), generate a log that mimics the experience of typing commands manually, and only keep specific input lines (like certain math formulas) in that log. Here are two practical solutions tailored to your needs:

方案1:用Bash脚本实现(适合非交互式命令)

如果你的testscript.scr里都是可以直接执行的非交互式命令,这个简单的Bash脚本就能搞定:

#!/bin/bash
LOGFILE="session.log"

# 先清空日志文件(可选,如果你想每次生成全新日志)
> "$LOGFILE"

# 逐行读取输入文件
while IFS= read -r cmd; do
    # 跳过空行
    [[ -z "$cmd" ]] && continue

    # 这里的条件判断可按需修改,示例是匹配类似"2+3=5"的数学公式
    if [[ "$cmd" =~ ^[0-9+*/-]+=[0-9]+$ ]]; then
        # 将需要保留的输入标记后写入日志
        echo ">>> $cmd" >> "$LOGFILE"
    fi

    # 执行命令,把输出(含错误)追加到日志,同时输出到终端(去掉| tee -a可只写日志)
    eval "$cmd" 2>&1 | tee -a "$LOGFILE"
done < "testscript.scr"

使用步骤:

  1. 将代码保存为run_and_log.sh
  2. 给脚本添加执行权限:chmod +x run_and_log.sh
  3. 运行脚本:./run_and_log.sh

自定义提示:

  • 若要保留特定前缀的行(比如行首是FORMULA:),把条件改成if [[ "$cmd" == FORMULA:* ]]
  • 如果不需要在终端看到输出,将| tee -a "$LOGFILE"替换为>> "$LOGFILE"

方案2:用Expect脚本实现(适合交互式命令)

如果你的命令需要等待特定响应再继续(比如输入密码、等待程序反馈的场景),expect工具会更适配。以下是示例脚本:

#!/usr/bin/expect
set logfile "session.log"
set scriptfile "testscript.scr"

# 开启日志追加模式
log_file -a $logfile

# 读取输入文件里的所有命令
set f [open $scriptfile r]
set cmds [split [read $f] "\n"]
close $f

# 遍历每个命令
foreach cmd $cmds {
    # 跳过空行
    if {$cmd eq ""} continue

    # 匹配要保留的数学公式(示例正则,可自定义)
    if {[regexp {^[0-9+*/-]+=[0-9]+$} $cmd]} {
        # 将保留的输入写入日志
        send_log ">>> $cmd\n"
    }

    # 发送命令到终端
    send "$cmd\r"
    # 等待命令执行完成,这里的正则匹配shell提示符(比如"$ ",root用户可改成"# ")
    expect -re {\$ $}
}

exit

使用步骤:

  1. 确保expect已安装:Ubuntu/Debian用apt install expect,CentOS/RHEL用yum install expect
  2. 保存脚本为run_and_log.exp
  3. 添加执行权限:chmod +x run_and_log.exp
  4. 运行脚本:expect run_and_log.exp

自定义提示:

  • 修改expect -re {\$ $}里的正则,匹配你实际使用的shell提示符
  • 调整regexp里的规则,精准匹配你需要保留的特定输入内容

内容的提问来源于stack exchange,提问作者ivo Welch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:45:59