Bash output is not putting the inputs in the correct spot

This is my file for reading lines from input.txt and printing them out.

#!/bin/bash
read -p "Enter an apartment number:" aptNumber
while IFS=$' \n' read -r firstName lastName leaseStart leaseEnd balance;
do
echo "Apartment Number: $aptNumber"
echo "Tenant Name: $lastName,$firstName"
echo "Lease Start: $leaseStart"
echo "Lease End: $leaseEnd"
echo "Current Balance: $balance"
done < input.txt

input.txt

John Doe
07/07/19 07/07/20
900

This is the output it’s giving me

Enter an apartment number:001
Apartment Number: 001
Tenant Name: Doe,John
Lease Start:
Lease End:
Current Balance:
Apartment Number: 001
Tenant Name: 07/07/20,07/07/19
Lease Start:
Lease End:
Current Balance:
Apartment Number: 001
Tenant Name: ,900
Lease Start:
Lease End:
Current Balance:

This is the output i need

Apartment Number: 001
Tenant Name: Doe,John
Lease Start: 07/07/19
Lease End: 07/07/20
Current Balance: 900

>Solution :

I suggest with bash:

read -r -p "Enter an apartment number:" aptNumber
while read -r first last; do
  read -r start end
  read -r balance
  echo "Apartment Number: $aptNumber"
  echo "Tenant Name: $last,$first"
  echo "Lease Start: $start"
  echo "Lease End: $end"
  echo "Current Balance: $balance"
done < input.txt

Every read in this loop reads one line of input.txt.

Output:

Enter an apartment number:42
Apartment Number: 42
Tenant Name: Doe,John
Lease Start: 07/07/19
Lease End: 07/07/20
Current Balance: 900

See help read for read’s options.

Leave a Reply