1

code.sh

This file contain following data

input="/path/data.txt"
while IFS= read -r line
do
 read -p 'Enter the name' name
  if(("$name"=="$line"))
   then  
  echo "matched"
  fi
done < "$input"

data.txt

This file contain following data

John
David
taker

I have 2 files. file one is code.sh and second data.txt. The above code in code.sh file only read data from data.txt. I want to access data from data.txt and conditional statement not working on $line. How can we apply operation on $line variable The above code we do not comparing string we want to use data that we access from txt file. After accessing data we will be to compare string.

john
  • 79
  • 7
  • 1
    It looks like code.sh already accesses data from data.txt and stores lines in a variable called line. What problem are you really facing? – mouviciel May 22 '21 at 16:57
  • The data store in line variable only readable I do not able to apply operation on line variable – john May 22 '21 at 16:58
  • 1
    Please update your question and explain what is the real goal is. – Jetchisel May 22 '21 at 17:02
  • I update the equation. – john May 22 '21 at 17:08
  • Your problem is you have redirected `"$input"` on the `stdin` file descriptor and then within the loop try to read `name` on `stdin` also. That won't work. Redirect `"$input"` on `fd3` and all is good, e.g. `while IFS= read -u 3 -r line ... done 3< "$input"`. You do need to fix your string comparison too, e.g. `if [ "$name" = "$line" ]` and I would fix the prompt too `read -p 'Enter the name: ' name` – David C. Rankin May 23 '21 at 07:26

1 Answers1

1

Continuing from my comment, your problem is you have redirected "$input" on the stdin file descriptor and then within the loop try to read name on stdin also. That won't work. You need to redirect input on another file descriptor so you can then read name on stdin, e.g.

#!/bin/bash

input="/path/data.txt"

while IFS= read -u 3 -r line                ## reads on fd3
do
 read -p 'Enter the name: ' name            ## reads name on stdin (fd0)
  if [ "$name" = "$line" ]
   then
  echo "matched"
  fi
done 3< "$input"                            ## input redirected on fd3

(note: the string equality test was also fixed as well as the prompt format for reading name)

Example Use/Output

$ bash test.sh
Enter the name: John
matched
Enter the name: David
matched
Enter the name: taker
matched

Let me know if you have further questions.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • This code give me error read illegal option `-u` – john May 23 '21 at 13:37
  • 1
    I'm not aware of any version of bash that doesn't provide the `-u` option for `"Read input from file descriptor fd."` What version do you have an what OS is it on? – David C. Rankin May 24 '21 at 20:33