How to make “if not true condition”?

后端 未结 6 1046
夕颜
夕颜 2020-12-22 15:56

I would like to have the echo command executed when cat /etc/passwd | grep \"sysa\" is not true.

What am I doing wrong?

if          


        
6条回答
  •  醉梦人生
    2020-12-22 16:18

    What am I doing wrong?

    $(...) holds the value, not the exit status, that is why this approach is wrong. However, in this specific case, it does indeed work because sysa will be printed which makes the test statement come true. However, if ! [ $(true) ]; then echo false; fi would always print false because the true command does not write anything to stdout (even though the exit code is 0). That is why it needs to be rephrased to if ! grep ...; then.

    An alternative would be cat /etc/passwd | grep "sysa" || echo error. Edit: As Alex pointed out, cat is useless here: grep "sysa" /etc/passwd || echo error.

    Found the other answers rather confusing, hope this helps someone.

提交回复
热议问题