简体   繁体   English

Bash中嵌套命令的STDOUT

[英]STDOUT of nested commands in Bash

Quite new to bash - I'm trying to store the output of my /usr/bin/time command into the TIME_INFO variable, which works with the below setup... however I would also like to be able to store the output of some of the other nested commands (such as /usr/local/bin/firejail or ./program) to other variables. bash相当新-我正在尝试将/ usr / bin / time命令的输出存储到TIME_INFO变量中,该变量可与以下设置一起使用...但是,我也希望能够存储某些输出其他嵌套命令(例如/ usr / local / bin / firejail或./program)中的其他命令。 Currently if there is a runtime exception in ./program it'll also go to the TIME_INFO variable. 当前,如果./program中存在运行时异常,则还将转到TIME_INFO变量。

TIME_INFO=$( /usr/bin/time --quiet -f "%e-%U-%S-%M-%x" 2>&1 \
timeout 5s \
/usr/local/bin/firejail --quiet --cgroup=/sys/fs/cgroup/memory/group1/tasks --profile=java.profile \
./program < test.in > test.out )

Is there any way to accomplish separating outputs of multiple nested commands? 有没有办法完成多个嵌套命令的输出分离?

Thanks in advance! 提前致谢!

One way to do this is to inject a shell in the call chain and make it responsible for modifying stderr for its subprocesses: 一种方法是在调用链中注入一个shell,并使它负责为其子进程修改stderr:

time_info=$( /usr/bin/time --quiet -f "%e-%U-%S-%M-%x" 2>&1 \
  sh -c '"$@" 2>"$0"' test.err \
    timeout 5s \
      /usr/local/bin/firejail \
          --quiet --cgroup=/sys/fs/cgroup/memory/group1/tasks --profile=java.profile \
        ./program < test.in > test.out )

# read your content back into a shell variable
error_text=$(<test.err)

The pertinent change here is sh -c '"$@" 2>"$0" , which runs its arguments as a command, with stderr redirected to the filename passed in $0 -- which is populated from the string immediately following code passed with sh -c . 此处的相关更改是sh -c '"$@" 2>"$0" ,它以命令的形式运行其参数,并将stderr重定向到$0传递的文件名-从紧随sh -c传递的代码之后的字符串中填充sh -c

Note that I modified the case of the TIME_INFO variable per POSIX guidance specifying all-caps names for variables with meaning to the shell or OS, and reserving names with at least one lower-case character for other purposes. 请注意,我根据POSIX指南修改了TIME_INFO变量的大小写,为具有外壳程序或OS含义的变量指定了全大写名称,并为其他目的保留了至少一个小写字符的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM