Bash:内联执行返回重复的“进程”。为什么?

tok*_*osh 6 linux bash

bash: 4.3.42(1)-release (x86_64-pc-linux-gnu)

执行以下脚本:

# This is myscript.sh
line=$(ps aux | grep [m]yscript)  # A => returns two duplicates processes (why?)
echo "'$line'"
ps aux | grep [m]yscript          # B => returns only one
Run Code Online (Sandbox Code Playgroud)

输出:

'tom   31836  0.0  0.0  17656  3132 pts/25   S+   10:33   0:00 bash myscript.sh
tom   31837  0.0  0.0  17660  1736 pts/25   S+   10:33   0:00 bash myscript.sh'
tom   31836  0.0  0.0  17660  3428 pts/25   S+   10:33   0:00 bash myscript.sh
Run Code Online (Sandbox Code Playgroud)

为什么内联执行的ps-snippet(A) 返回两行?

Joh*_*024 3

概括

这将创建一个子 shell,因此有两个进程正在运行:

line=$(ps aux | grep [m]yscript) 
Run Code Online (Sandbox Code Playgroud)

这不会创建子 shell。因此,myscript.sh只有一个进程在运行:

ps aux | grep [m]yscript       
Run Code Online (Sandbox Code Playgroud)

示范

让我们稍微修改一下脚本,以便将进程和子进程 PID 保存在变量中line

$ cat myscript.sh 
# This is myscript.sh
line=$(ps aux | grep [m]yscript; echo $$ $BASHPID)
echo "'$line'"
ps aux | grep [m]yscript  
Run Code Online (Sandbox Code Playgroud)

在 bash 脚本中,$$是脚本的 PID,在子 shell 中保持不变。相比之下,当输入子 shell 时,bash 会$BASHPID使用子 shell 的 PID 进行更新。

这是输出:

$ bash myscript.sh 
'john1024  30226  0.0  0.0  13280  2884 pts/22   S+   18:50   0:00 bash myscript.sh
john1024   30227  0.0  0.0  13284  1824 pts/22   S+   18:50   0:00 bash myscript.sh
30226 30227'
john1024   30226  0.0  0.0  13284  3196 pts/22   S+   18:50   0:00 bash myscript.sh
Run Code Online (Sandbox Code Playgroud)

在本例中,30226 是主脚本上的 PID,30227 是正在运行的子 shell 的 PID ps aux | grep [m]yscript