Skip to content
Advertisement

How to use error validation in Bash for checking an entry in a file

JavaScript

If there is no entry of that species name in the file how do I give the user an error to say not found?

Advertisement

Answer

The answer to your immediate question is to examine the exit code from grep. But probably also refactor the loop:

JavaScript

A better design altogether is probably to make the search term a command-line argument. This makes the script easier to use from other scripts, and the user can use the shell’s facilities for history, completion, etc to run it as many times as they like, and easily fix e.g. typos by recalling the previous invocation and editing it.

JavaScript

The short-circuit one || two corresponds to the longhand

JavaScript

If you want to search for static strings, not regular expressions, maybe add -F to the grep options.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement