带有 STDERR/STDOUT 重定向的 eval 命令导致问题

eval commands with STDERR/STDOUT redirection causing problems

我正在尝试编写一个 bash 脚本,其中每个命令都通过一个使用此行评估命令的函数传递:

eval  2>&1 >>~/max.log | tee --append ~/max.log

它不起作用的一个例子是在尝试评估 cd 命令时:

eval cd /usr/local/src 2>&1 >>~/max.log | tee --append ~/max.log

导致问题的部分是 | tee --append ~/max.log 部分。知道我为什么遇到问题吗?

来自 bash(1) 手册页:

Each command in a pipeline is executed as a separate process (i.e., in a subshell).

因此,cd 在管道中使用时,不能更改当前shell的工作目录。要解决此限制,通常的方法是将 cd 与其他命令组合在一起并重定向该组命令的输出:

{
    cd /usr/local/src
    command1
    command2
} | tee --append ~/max.log

在不破坏现有设计的情况下,您可以在过滤器函数中专门处理 cd

# eval all commands (will catch any cd output, but will not change directory):
eval  2>&1 >>~/max.log | tee --append ~/max.log
# if command starts with "cd ", execute it once more, but in the current shell:
[[ "" == cd\ * ]] && 

根据您的情况,这可能还不够:您可能必须处理其他修改环境的命令或 shell 变量,例如 sethistoryulimitreadpushdpopd。在那种情况下,重新考虑程序的设计可能是个好主意。