Grep

當它與字元串不匹配時,整數 grep 返回什麼退出程式碼?

  • June 16, 2018

當它與字元串不匹配時,整數 grep 返回什麼退出程式碼?

我知道它在匹配時返回 0,我假設它在不匹配時返回 1。

那是對的嗎?

man grep幫助:

EXIT STATUS
   The grep utility exits with one of the following values:

   0     One or more lines were selected.
   1     No lines were selected.
   >1    An error occurred.

此外,對於GNU Grep

However, if the -q or --quiet or --silent option is used and a line is
selected, the exit status is 0 even if an error occurred. Other grep 
implementations may exit with status greater than 2 on error.

並且,根據實現:

Normally, exit status is 0 if matches were found, and 1 if
no  matches  were found.  (The -v option inverts the sense
of the exit status.)

要測試自己,請將以下內容放入腳本並執行它。

#!/bin/bash
echo -n "Match: "
echo grep | grep grep >/dev/null; echo $?
echo -n "Inverted match (-v): "
echo grep | grep -v grep; echo $?
echo -n "Nonmatch: "
echo grep | grep grepx; echo $?
echo -n "Inverted nonmatch (-v): "
echo grep | grep -v grepx >/dev/null; echo $?
echo -n "Quiet match (-q): "
echo grep | grep -q grep; echo $?
echo -n "Quiet nonmatch (-q): "
echo grep | grep -q grepx; echo $?
echo -n "Inverted quiet match (-qv): "
echo grep | grep -qv grep; echo $?
echo -n "Inverted quiet nonmatch (-qv): "
echo grep | grep -qv grepx; echo $?

引用自:https://unix.stackexchange.com/questions/450176