I would like to have the echo command executed when cat /etc/passwd | grep "sysa" is not true.
What am I doing wrong?
if ! [ $(cat /etc/passwd | grep "sysa") ]; then
echo "ERROR - The user sysa could not be looked up"
exit 2
fi
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
try
grepreturnstrueif it finds the search target, andfalseif it doesn’t.So NOT false (
! false) ==true.ifevaluation in shells are designed to be very flexible, and many times doesn’t require chains of commands (as you have written).Also, looking at your code as is, your use of the
$( ... )form of cmd-substitution is to be commended, but think about what is coming out of the process. Tryecho $(cat /etc/passwd | grep "sysa")to see what I mean. You can take that further by using the-c(count) option to grep and then doif ! [ $(grep -c "sysa" /etc/passwd) -eq 0 ] ; thenwhich works but is rather old school.BUT, you could use the newest shell features (arithmetic evaluation) like
which also gives you the benefit of using the c-lang based comparison operators,
==,<,>,>=,<=,%and maybe a few others.In this case, per a comment by Orwellophile, the arithmetic evaluation can be pared down even further, like
OR
Finally, there is an award called the
Useless Use of Cat (UUOC). 🙂 Some people will jump up and down and cry gothca! I’ll just say thatgrepcan take a file name on its cmd-line, so why invoke extra processes and pipe constructions when you don’t have to? 😉I hope this helps.