Here’s my current code, the idea was to get details from a text file, split it up with the truncate, and output text in a readable way.
patron.txt only has this line:
123456:Gerald:010-9999999:asdf@gmail.com
The idea was for to make an array with 4 parts, each read individually, and input into the echo one by one.
The terminal instead is just showing a blank line.
I heard printf can do the trick but I dunno how to make heads or tails with that, at least in bash.
#!/bin/bash
echo "Search Patron Details"
echo -n "Enter Patron ID: "
read id1
grep -i -q "$id" patron.txt
array=$(echo $id | tr ":" "\n")
for fill in $array
do
$loop++
if [$loop == 0]
then
:
elif [$loop == 1]
then
echo "Fullname (auto display): $fill"
elif [$loop == 2]
then
echo "Contact Number (auto display): $fill"
elif [$loop == 3]
then
echo "Email Adddress (auto display): $fill"
else
while [$loop = true]
do
echo -n "Search another patron? (y)es or (q)uit"
read choice
case $choice in
y|Y) bash show_details;;
q|Q) exit;;
*) echo "Invalid input!"
esac
done
fi
done
echo "$id"
>Solution :
There are a number of problems with your code.
First, you’re prompting for a patron id and storing that in the id1 variable, but you never use that variable anywhere else in your code.
Second, this does nothing:
grep -i -q "$id" patron.txt
Even if you were using the correct variable, this command is effectively a no-op: it generates no output (because of the -q), and even if it did you’re not doing anything with it. You’re also ignoring the exit code.
This:
array=$(echo $id | tr ":" "\n")
Also does nothing useful: even if you were using the id1 variable, you’re just echoing the variable to tr and not making use of the contents of your patron.txt file.
Lastly, you probably want to use mapfile to populate your array variable.
Something like this:
#!/bin/bash
echo "Search Patron Details"
echo -n "Enter Patron ID: "
read id1
mapfile -d: -t array < <(grep -i "$id1" patron.txt)
echo "Fullname (auto display): ${array[1]}"
echo "Contact Number (auto display): ${array[2]}"
echo "Email Adddress (auto display): ${array[3]}"
With your sample data in patron.txt, running this looks like:
Search Patron Details
Enter Patron ID: 123456
Fullname (auto display): Gerald
Contact Number (auto display): 010-9999999
Email Adddress (auto display): asdf@gmail.com