vicence
V2EX  ›  Linux

这命令echo `ps aux|grep $0|grep -v grep|mawk '{print $3}'`在终端输出是一个数值, 在脚本中会输出两个值,为什么?

By vicence at 2013 年 11 月 28 日 · 8855 次点击
脚本如下:

#!/bin/bash
# using recursion



# cpu使用率

echo `ps aux|grep $0|grep -v grep|mawk '{print $3}'`
5 条回复  •  1970-01-01 08:00:00 +08:00
qmake
   1
qmake  
   2013 年 11 月 28 日
有一个是当前脚本的进程?
BOYPT
   2
BOYPT  
   2013 年 11 月 28 日
其实写成这样就能看出区别:

echo `ps aux|grep $0|grep -v grep|mawk '{print $3}'`
ps aux|grep $0|grep -v grep|mawk '{print $3}'



第一行还是输出两个的。

因为是在子shell里面运行,里面的$0和外面的不一样。
vicence
   3
vicence  
OP
   2013 年 11 月 29 日
@BOYPT 但如果想取ps aux|grep $0|grep -v grep|mawk '{print $3}'的值,
num=`ps aux|grep $0|grep -v grep|mawk '{print $3}'`
echo $num
这样值还是两个
BOYPT
   4
BOYPT  
   2013 年 11 月 29 日
@vicence 只要放在``里面就就是子shell了啊,只要是子shell那一定就不对了。
Jesse
   5
Jesse  
   2013 年 11 月 29 日
@vicence

# A: fine
echo `ps aux|grep $$|grep -v grep|awk '{print $3}'`

# B : fine
ps aux|awk '($2 == PROCINFO["ppid"]){print $3}'

# C : better
export shpid=$$
echo `ps aux|awk '($2 == ENVIRON["shpid"]){print $3}'`
Distributions
› Ubuntu
› Fedora
› CentOS
中文资源站
› 网易开源镜像站
© 2026 V2EX · 33ms · 3.9.8.5