代码之家  ›  专栏  ›  技术社区  ›  ProfessorManhattan

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

  •  4
  • ProfessorManhattan  · 技术社区  · 10 年前

    我正在尝试编写一个bash脚本,其中每个命令都通过一个函数传递,该函数使用以下行对命令求值:

    eval $1 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。日志部分。知道我为什么会遇到问题吗?

    1 回复  |  直到 10 年前
        1
  •  6
  •   Michael Jaros    10 年前

    bash(1) 手册页:

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

    因此 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 $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
    

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