ps linux 中的命令
ps command in linux
我是类 unix 的新手。而且我遇到了一个奇怪的问题,我真的无法通过搜索找到答案。
#!/bin/bash
me=`basename "[=12=]"`
echo $(ps -e | grep "$me" | wc -l)
ps -e | grep "$me" | wc -l
执行完 bash 脚本后,回显显示 2,而 ps 只显示 1,这正是我想要的。这怎么会发生?为什么 echo 向我显示了一个额外的进程?
正如查尔斯·达菲指出的那样,$() creates a subshell
。这回答了我的问题。显然我还有很多东西要学。感谢大家的帮助。
正如 Cyrus 的评论所指出的;这个脚本:
me=$(basename [=10=])
ps -ef |grep $me
使用“./ps.sh”启动时,打印:
auser@pc:/tmp$ ./ps.sh
auser 4425 4422 0 08:42 pts/3 00:00:00 grep ps.sh
auser@pc:/tmp$
这里不涉及子 shell,ps(1) 列出的是 grep(1) 本身。相同的脚本,以 "bash ps.sh" 输出启动:
auser 4426 3946 0 08:44 pts/3 00:00:00 bash ps.sh
auser 4429 4426 0 08:44 pts/3 00:00:00 grep ps.sh
这是 OP 得到的结果,即使没有子 shell。更明确:
auser@pc:/tmp$ ps -ef |grep grep
auser 4467 3946 0 08:49 pts/3 00:00:00 grep grep
尽管您正在使用 $()
创建一个子 shell,但您可以使用 grep -v grep
.
将其 grep 出来
所以:
$(ps -e | grep "$me" | grep -v grep | wc -l)
这将 return 1 而不是 2
我是类 unix 的新手。而且我遇到了一个奇怪的问题,我真的无法通过搜索找到答案。
#!/bin/bash
me=`basename "[=12=]"`
echo $(ps -e | grep "$me" | wc -l)
ps -e | grep "$me" | wc -l
执行完 bash 脚本后,回显显示 2,而 ps 只显示 1,这正是我想要的。这怎么会发生?为什么 echo 向我显示了一个额外的进程?
正如查尔斯·达菲指出的那样,$() creates a subshell
。这回答了我的问题。显然我还有很多东西要学。感谢大家的帮助。
正如 Cyrus 的评论所指出的;这个脚本:
me=$(basename [=10=])
ps -ef |grep $me
使用“./ps.sh”启动时,打印:
auser@pc:/tmp$ ./ps.sh
auser 4425 4422 0 08:42 pts/3 00:00:00 grep ps.sh
auser@pc:/tmp$
这里不涉及子 shell,ps(1) 列出的是 grep(1) 本身。相同的脚本,以 "bash ps.sh" 输出启动:
auser 4426 3946 0 08:44 pts/3 00:00:00 bash ps.sh
auser 4429 4426 0 08:44 pts/3 00:00:00 grep ps.sh
这是 OP 得到的结果,即使没有子 shell。更明确:
auser@pc:/tmp$ ps -ef |grep grep
auser 4467 3946 0 08:49 pts/3 00:00:00 grep grep
尽管您正在使用 $()
创建一个子 shell,但您可以使用 grep -v grep
.
所以:
$(ps -e | grep "$me" | grep -v grep | wc -l)
这将 return 1 而不是 2