Home > Enterprise >  How to write if-else statement if the user input is matched or unmatched with the record in text fil
How to write if-else statement if the user input is matched or unmatched with the record in text fil

Time:03-19

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|[email protected]
21PMR07123|John|012-3456789|[email protected]
21PMR07221|Amy|017-4567890|[email protected]

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

CodePudding user response:

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.

  • Related