【问题标题】:Bash - Hiding a command but not its outputBash - 隐藏命令但不隐藏其输出
【发布时间】:2015-05-14 20:46:45
【问题描述】:

我有一个调用另一个 TCL 脚本的多个实例的 bash 脚本 (this_script.sh)。

set -m
for vars in $( cat vars.txt );
do
   exec tclsh8.5 the_script.tcl "$vars" &
done
while [ 1 ]; do fg 2> /dev/null; [ $? == 1 ] && break; done

多线程部分取自 Aleksandr 的回答:Forking / Multi-Threaded Processes | Bash。 该脚本运行良好(仍在尝试找出最后一行)。但是,这条线总是显示:exec tclsh8.5 the_script.tcl "$vars"

如何隐藏该行?我尝试将脚本运行为:

bash this_script.sh > /dev/null

但这也隐藏了调用的 tcl 脚本的输出(我需要 TCL 脚本的输出)。 我尝试将 /dev/null 添加到 for 语句中的语句末尾,但这也不起作用。基本上,我试图隐藏命令而不是输出。

【问题讨论】:

  • 你为什么不改用wait
  • for vars in $(<vars.txt)? < vars.txt while read -r vars?
  • 作为wait 的替代品,您可以使用GNU parallel 甚至只使用xargs 来并行运行。 (顺便说一句,这不是多线程,它只是多个进程。)
  • exec 在这里为您做什么?从这样的文件中读取值是不安全的 (mywiki.wooledge.org/DontReadLinesWithFor)。那条线在哪里显示?流程何时结束?
  • 脚本一启动,就会显示该行。如果我不使用 exec,那么这仍然显示:tclsh8.5 the_script.tcl "$vars"

标签: bash tcl expect


【解决方案1】:

您应该使用$! 来获取刚刚启动的后台进程的PID,将它们累积在一个变量中,然后在第二个for 循环中依次为每个进程使用wait

set -m
pids=""
for vars in $( cat vars.txt ); do
   tclsh8.5 the_script.tcl "$vars" &
   pids="$pids $!"
done
for pid in $pids; do
   wait $pid
   # Ought to look at $? for failures, but there's no point in not reaping them all
done

【讨论】:

  • 为什么 wait 单独而不是同时 wait 单独使用?
  • 当我使用此方法时,脚本以消息开头:this_script.sh: line 15: pids: command not found
  • @user2883071 你在某处使用过pid =(带空格)吗?
  • 我没有在任何地方那样使用它,我以完全相同的方式输入它。但是,即使我收到该消息,该脚本仍然有效。然而,另一个问题出现了。一旦脚本完成,它会在一个空白行停止(因此用户将不知道它是否仍在运行)。我之前解决这个问题的方法是实现 Aleksandrs 方法。
  • @user2883071 如果您到处都有pids=,那么您应该不会看到“找不到命令”错误。那个 sn-p 中也没有 15 行,那么第 15 行适合你吗?
猜你喜欢
  • 2013-08-06
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 2012-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-06
相关资源
最近更新 更多