1

Why the read function inside this while loop not working? if i uncomment echo (and comment read) it prints several times, but if the "read" is uncommented it just exits function. Same "read" works outside loop.

readTest()
{
  ls -l | while read -r files; do
    read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
    #echo "tttt"
  done

}
0

2 Answers 2

4

Both the read in the while line and the read in the loop body will read from the pipe, not from the terminal. The output from ls does not match the patterns, so the exit command will be called.

Parsing the output of ls is error-prone. You should better use something like

for files in *; do
    read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
    #echo "tttt"
done

This would avoid the input redirection for the inner read.

If you don't need to exit from the whole shell script, I suggest break or return instead of exit.


More detailed explanation to answer a comment

In a simplified example

ls | while read -r files; do
    read confirm
done

and assuming ls prints

foo
bar
baz

in the first iteration, read -r files will get foo, then read confirm will get bar,
in the second iteration, read -r files will get baz, then read confirm will get EOF,
in the third iteration, read -r files will get EOF and terminate the loop.

2
  • wont the pipe exit when the ls finishes? @Bodo ? Commented Jan 27, 2023 at 1:24
  • 1
    @Nasir see More detailed explanation Commented Jan 27, 2023 at 9:47
0

@bodo explained this correctly, but:

Whenever you have this pattern and you can't avoid using while (i.e. replace it with for-loop or something), this could help:

important_command | while read -r stuff; do
    read -p "Continue? (Y/N): " confirm < /dev/tty
    
    if [[ "${confirm,,}" =~ ^(y|yes)$ ]]; then
        do_important_stuff_with $stuff
    fi
done

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.