Skip to content
Advertisement

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

#!/bin/bash

echo 'Please enter the name of the species you are looking for: '

read speciesName

grep "$speciesName" speciesDetails.txt | awk '{print $0}'
echo
echo 'Would you like to search for another species? Press y to search or n to go back 
to the main menu: ' 
read answer

case $answer in
[yY] | [yY][eE][sS] )
    ./searchSpecies.sh;;
[nN] | [nN][oO] )
    ./speciesMenu.sh;;
*) echo exit;;
esac

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:

#!/bin/bash

while true; do
    read -p 'Please enter the name of the species you are looking for: ' -r speciesName
    grep -e "$speciesName" speciesDetails.txt || echo "$speciesName: not found" >&2

    read -p 'Would you like to search for another species? Press n to quit: ' -r answer
    case $answer in
     [nN] | [nN][oO] )
        break;;
    esac
done

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.

#!/bin/bash
grep -e "$1" speciesDetails.txt || echo "$1: not found" >&2

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

if one; then
    : nothing
else
    two
fi

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