Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash grep的多个同时模式_Bash_Grep - Fatal编程技术网

Bash grep的多个同时模式

Bash grep的多个同时模式,bash,grep,Bash,Grep,我需要查看用户是否存在于/etc/passwd中。我正在使用grep,但是我很难将多个模式传递给grep 我试过了 if [[ ! $( cat /etc/passwd | egrep "$name&/home" ) ]];then #user doesn't exist, do something fi 我使用了符号而不是|,因为这两个条件都必须为真,但它不起作用。尝试这样做: $ getent passwd foo bar base 最后: if getent &&

我需要查看用户是否存在于
/etc/passwd
中。我正在使用grep,但是我很难将多个模式传递给grep

我试过了

if [[ ! $( cat /etc/passwd | egrep "$name&/home" ) ]];then
   #user doesn't exist, do something
fi
我使用了符号而不是|,因为这两个条件都必须为真,但它不起作用。

尝试这样做:

$ getent passwd foo bar base
最后:

if getent &>/dev/null passwd user_X; then
    do_something...
else
    do_something_else...
fi

与您的假设相反,正则表达式不识别交叉点的
&
,即使它是一个逻辑扩展

要查找匹配多个图案的线条,请尝试

grep -e 'pattern1.*pattern2' -e 'pattern2.*pattern1' file
要以任何顺序匹配模式,或切换到Awk,请执行以下操作:

awk '/pattern1/ && /pattern2/' file
(尽管在您的特定示例中,只要
“$name.*/home”
就足够了,因为匹配必须始终按此顺序进行)

另外,您扭曲的
if
条件可以重构为

if grep -q pattern file; then ...

if
条件将命令作为其参数,运行它,并检查其退出代码。任何正确编写的Unix命令都会写入此规范,并在成功时返回零,否则返回非零退出代码。(还要注意没有无用的
cat
——几乎所有命令都接受文件名参数,不接受的命令可以通过重定向处理。)

谢谢,为了美观,请选择
getent