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

use*_*265 4 bash cd eval tee

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

eval $1 2>&1 >>~/max.log | tee --append ~/max.log
Run Code Online (Sandbox Code Playgroud)

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

eval cd /usr/local/src 2>&1 >>~/max.log | tee --append ~/max.log
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*ros 6

bash(1)手册页:

管道中的每个命令都作为单独的进程(即,在子外壳中)执行。

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

{
    cd /usr/local/src
    command1
    command2
} | tee --append ~/max.log
Run Code Online (Sandbox Code Playgroud)

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

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

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