Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write if-else statement if the user input is matched or unmatched with the record in text file in bash?

I currently have a text file called student.txt and there are some records in the text file.
The format of the records are StudentID|Name|ContactNumber|EmailAddress and the records are as follows:

21PMR07222|Steven|011-1234567|steven@yahoo.com
21PMR07123|John|012-3456789|john@yahoo.com
21PMR07221|Amy|017-4567890|amy@gmail.com

How to put the following code into if-else statement where if the student ID entered by user is matched with the student ID in the text file, the details of the student will be displayed, else error message "The student ID does not exist. Please enter again." will be displayed.

awk -F'|' -v id="$studentID" '$1 == id { printf "Name: %s\nContact Number: %s\nEmail Address: %s\n", $2, $3, $4 }' < student.txt

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One idea:

awk -F'|' -v id="$studentID" '
$1 == id { found=1; printf "Name: %s\nContact Number: %s\nEmail Address: %s\n", $2, $3, $4 }
END      { if (found==0) printf "The student ID does not exist. Please enter again." }
' student.txt

NOTES:

  • this awk code is not going to prompt the user for a new studentID
  • the parent code will need to be able to capture and parse the awk output to determine if it should ask the user a new question; alternatively …
  • the awk code could return a non-0 status that the parent code could use to determine if the user should be prompted to enter a new studentID

Have awk return a non-0 status code that the parent code can use for follow-on processing:

awk -F'|' -v id="$studentID" '
$1 == id { found=1
           printf "Name: %s\nContact Number: %s\nEmail Address: %s\n", $2, $3, $4
         }
END      { if (found==0) {
              printf "The student ID does not exist. Please enter again." 
              exit 1
           }
         }
' student.txt

awk_exit_status=$?

The default exit status of an awk script is 0 (ie, no issues). The END{...} block will generate an exit status of 1 if found==0.

The bash variable awk_exit_status will contain either a 0 (Name: ... Contact Number ... Email Address ...) or 1 (The student ID does not exist) which the parent bash script can then use to determine how to proceed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading