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

Time:10-10

#!/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?

CodePudding user response:

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 "$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 "$1" speciesDetails.txt || echo "$1: not found" >&2

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

if one; then
    : nothing
else
    two
fi

CodePudding user response:

Use $? to check exit code of the command

0 == found

MINGW64 ~
$ echo "speciesName1" > speciesDetails.txt
$ echo "speciesName2" >> speciesDetails.txt
$ echo "speciesName3" >> speciesDetails.txt

$ grep speciesName3 speciesDetails.txt
speciesName3
$ echo $?
0

$ grep speciesName4 speciesDetails.txt
$ echo $?
1
  • Related