【发布时间】:2016-09-09 01:35:18
【问题描述】:
这个人为的 bash 脚本演示了这个问题。
#!/bin/bash
while read -r node ; do
echo checking $node for Agent;
PID=$(ssh $node ""ps -edf | grep [j]ava | awk '{print $2}'"")
echo $PID got to here.
done < ~/agents_master.list
agents_master.list 每行包含 1 个服务器:
server1
server2
server3
仅输出以下内容:
checking server1 for Agent
Authorized use only
25176 got to here
服务器 2 和 3 甚至没有通过 echo checking $node... 行回显到屏幕
如果我注释掉PID=$(.... 行,那么while 将正确完成整个agents_master.list 文件...
checking server1 for Agent
got to here
checking server2 for Agent
got to here
checking server3 for Agent
got to here
从我所做的谷歌搜索来看,这听起来与$(...) 创建的子shell 有关,但我不明白为什么它会导致循环在第一台服务器server1 处停止。
是的,这段代码可以重写,但我很想了解 bash 的这种行为以及为什么会在未来发生这种情况。
【问题讨论】:
-
PID=$(ps -edopid=,command= | awk '/[j]ava/{print $1}')为您节省了管道和浪费的过程。假设您使用的是 Linux。
标签: bash shell while-loop subshell