shell中`|`符号是什么意思?

Aam*_*mir 16 command-line bash process

命令中的|符号是什么意思sudo ps -ef | grep processname

也有人可以解释一下这个命令吗?我仅使用此命令来获取 PID 并终止该进程,但我也看到sudo ps -ef | grep processname | grep -v grep并且我的印象-v grep是,这就像杀死grep. 如果是这样,它是如何工作的?

Par*_*rto 35

它被称为pipe。它将第一个命令的输出作为第二个命令的输入。

在您的情况下,这意味着:
结果sudo ps -ef作为输入grep processname

sudo ps -ef:
这列出了所有正在运行的进程。键入man ps在termial更多。

grep processname
所以,这个进程列表被输入到 grep 中,它只搜索由programname.

例子

sudo ps -ef | grep firefox在我的终端中输入返回:

parto     6501  3081 30 09:12 ?        01:52:11 /usr/lib/firefox/firefox
parto     8295  3081  4 15:14 ?        00:00:00 /usr/bin/python3 /usr/share/unity-scopes/scope-runner-dbus.py -s web/firefoxbookmarks.scope
parto     8360  8139  0 15:14 pts/24   00:00:00 grep --color=auto firefox
Run Code Online (Sandbox Code Playgroud)


Pil*_*ot6 13

ps -ef | grep processname
Run Code Online (Sandbox Code Playgroud)

它首先运行sudo ps -ef并将输出传递给第二个命令。

第二个命令过滤所有包含单词“processname”的行。

ps -ef | grep processname | grep -v grep列出包含processname和不包含的所有行grep

根据 man grep

-v, --invert-match
              Invert the sense of matching, to select non-matching lines.  (-v
              is specified by POSIX.)
Run Code Online (Sandbox Code Playgroud)

根据 man ps

ps displays information about a selection of the active processes.

-e     Select all processes.  Identical to -A.

-f     Do full-format listing. This option can be combined with many
          other UNIX-style options to add additional columns.  It also
          causes the command arguments to be printed.  When used with -L,
          the NLWP (number of threads) and LWP (thread ID) columns will be
          added.  See the c option, the format keyword args, and the
          format keyword comm.
Run Code Online (Sandbox Code Playgroud)

您可以组合参数-ef-e -f.

实际上ps -ef | grep processname列出所有出现的过程称为processname.


Gew*_*ure 6

我会尝试用一个直接的实用答案来回答这个问题:

管道|可以让你在 shell 中做一些很棒的事情!这是我认为最有用和最强大的单一操作符。

如何计算目录中的文件?简单的:

ls | wc -l..将行的lsto wcwit 参数的输出重定向-l

或计算文件中的行数?

cat someFile | wc -l
Run Code Online (Sandbox Code Playgroud)

如果我想搜索一些东西怎么办?'grep' 可以搜索字符串的出现:

cat someFile | grep aRandomStringYouWantToSearchFor
Run Code Online (Sandbox Code Playgroud)

您只需将管道左侧的命令输出重定向到管道右侧的命令。

再上一层:文件中某事发生的频率是多少?

cat someFile | grep aRandomStringYouWantToSearchFor | wc -l
Run Code Online (Sandbox Code Playgroud)

您可以使用 | 几乎所有东西:)

fortune | cowsay
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 是的,管道很有趣,+1,但请更改示例:[UUOC](http://porkmail.org/era/unix/award.html#cat)。 (2认同)