TheExel80 TheExel80 - 4 months ago 46
Bash Question

How i do correct while loop, which read two files

I have tried to do

.sh
script which read two file. Currently i got this error
line 7: file1: No such file or directory


user & city files are in same folder as script.

#!/bin/bash
file1='user.txt'
file2='city.txt'

while read -r -u 4 line1 && read -r -u 5 line2; do
echo "Output-1: $line1 & Output-2: $line2"
done 4<file1 5<file2

Answer

This error is trying to tell you that there is no such file named "file1":

file1: No such file or directory

It's not "file1" you want to read input from, but "user.txt", which is in the value of the variable file1. To do that, write $file1 instead of file1, like this:

#!/bin/bash
file1='user.txt'
file2='city.txt'

while read -r -u 4 line1 && read -r -u 5 line2; do
  echo "Output-1: $line1 & Output-2: $line2"
done 4<"$file1" 5<"$file2"