如何优化这两行 bash 代码

How to optimize this 2 lines of bash code

我想使用 1 行而不是两行来优化 bash 代码 这是我要优化的行:

grep -E "$name" /etc/passwd
if [ $? -eq 0 ]
     #...

所以 if 将测试最后一个命令 (grep) 的退出,我想合并 "grep -E "$name" /etc/passwd" 在 if 语句中有类似的东西:

if [ ##### -eq 0 ]

感谢您的帮助:)

可以直接在if语句中使用命令的退出码:

if grep .... 
then
  echo "found"
else
  echo "not found"
fi

如果你想静音 grep 命令的输出你可以添加 -q 选项,如果你想在第一次匹配后退出(在大文件上节省时间)你可以使用 -m 1.

没有 if:

grep "name" file && do_something