I am trying to come up with a script that will let the user read one line of the text file on each input of enter key until the file is done. What i tried so far:
while read -r line
do read input
if [[ -z $input ]]; then
echo $line
done < file.txt
or
while read -r line
echo | echo $line
done < file.txt
with the error:
sh: -c: line 3: syntax error near unexpected token `done'
sh: -c: line 3: `done < file.txt'
update: i forgot "fi" at the end of "if". however,
while IFS= read -r line
do
read input
if [[ -z $input ]]
then
echo $line
fi
done < filename.txt
This time i am not getting any error, but it does not expect my enter input and does not print anything.
CodePudding user response:
Update: solved by replacing
read input
with
read input </dev/tty
CodePudding user response:
read
reads from standard input by default. Your standard input is set to a file (< filename.txt
). bash however lets you specify the fd to read from:
$ cat test
line 1
line 2
line 3
You received only some lines from filename.txt
while others are consumed by read -r line
:
$ while IFS= read line; do
read line
echo $line
done < test
line 2
Here's how to use a different fd:
$ while IFS= read -u4 line; do
read -s
echo $line
done 4< test
line 1
line 2
line 3
See man page of bash (or whatever shell you are using) for the read
command.