I have a file that contains directory names:
my_list.txt :
/tmp
/var/tmp
I’d like to check in Bash before I’ll add a directory name if that name already exists in the file.
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.
The exit status is 0 (true) if the name was found, 1 (false) if not, so:
Explanation
Here are the relevant sections of the man page for
grep:Error handling
As rightfully pointed out in the comments, the above approach silently treats error cases as if the string was found. If you want to handle errors in a different way, you’ll have to omit the
-qoption, and detect errors based on the exit status:To suppress the normal output from
grep, you can redirect it to/dev/null. Note that standard error remains undirected, so any error messages thatgrepmight print will end up on the console as you’d probably want.To handle the three cases, we can use a
casestatement: