【问题标题】:Saving input before running command bash在运行命令 bash 之前保存输入
【发布时间】:2021-08-12 22:47:08
【问题描述】:

我正在尝试将我输入的命令及其各自的输出保存在一个文件中。
我目前在做什么:

mylog() {
    echo "----------------" >> ${PWD}/cmds.log
    echo "$@" >> ${PWD}/cmds.log
    # read foo # Tried reading the piped value in to
    # echo "$foo" >> ${PWD}/cmds.log
    # MYCMD="${@}"
    # echo "$MYCMD" >> ${PWD}/cmds.log
    "$@" | tee -a ${PWD}/cmds.log
}

它目前的功能类似于:mylog cat file.txt | mylog sort
cmds.log 中的输出是:

----------------
cat file.txt
----------------
sort
....
output from cat
...
output from sort
...

我想要的是:

----------------
cat file.txt
....
output from cat
...
----------------
sort
...
output from sort
...

在代码中,您可以看到我尝试使用 read 并遵循here 描述的其他方法。
我也尝试过VAR=${@},但这只是保存了两次命令并没有执行它。

知道如何实现我的目标吗?

有点相关,我像这样手动保存终端输出,而不是使用script,因为交互式外壳会导致很多转义字符等被捕获。

【问题讨论】:

  • 如果你想去掉交互式提示,将PS1 设置为'' 是否有效?顺便说一句,输出是这样的,因为管道中的所有片段都是并行运行的,而不是顺序运行的。
  • @dibery 我的 shell 的类型完成会导致建议输出的每个变体,所以 PS1='' 没有帮助。我怎样才能按顺序运行它们?

标签: bash


【解决方案1】:

您修改后的脚本...

#!/usr/bin/env bash

mylog() {
    local output="log"
    
    # This is the key part right here. The 'tac' command here
    # prints stdin in reverse. To do this, it must read _all_
    # of stdin, so it buffers until it reads everything. Of course,
    # we must use two 'tac's so stdin doesn't actually get reversed.
    # You could also use `sponge(1)` here, but that does not come standard
    # on all Linux distributions / MacOS
    local buffer="$("$@" | tac | tac)"

    # Nothing below will be printed until 'buffer' is completely filled with stdin
    {
        echo "----------------"
        echo "$@"
        echo "----------------"
        echo "$buffer"
        echo
    } >> "$output"

    printf "%s" "$buffer" 
}

rm -f log
mylog cat file.txt | mylog sort >/dev/null

生成的log

----------------
cat file.txt
----------------
bravo
alfa
charlie
delta
echo

----------------
sort
----------------
alfa
bravo
charlie
delta
echo


【讨论】:

  • 谢谢你的代码和解释!
猜你喜欢
  • 1970-01-01
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-12
  • 2017-02-05
  • 2017-10-15
相关资源
最近更新 更多