0

I got this function:

#!/bin/bash
prompt() {
read -r -p "${1:-Usunąć podany plik? [t/N]} " response
case "$response" in
    [tT][eE][sS]|[tT])
        true
        echo "Usuwam... $line"
        ;;
        *)
        false
        echo "Pomijam... $line"
        ;;
esac
}

And I want it to work inside a loop that reads line by line from a .txt file:

while IFS= read -r line
        do
            echo "$line" && prompt
        done < lista.txt

As I run the script here's the output (it doesn't actually prompt for user input):

11M /home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI2.pdf
Pomijam... 11M /home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI2.pdf
11M /home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI4.pdf
Pomijam... 11M /home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI4.pdf
11M /home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI6.pdf
Pomijam... 11M /home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI6.pdf

The lista.txt file looks like that if I use this loop:

while IFS= read -r line
        do
            echo "$line"
        done < lista.txt

Output:

11M /home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI2.pdf
11M /home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI3.pdf
11M /home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI4.pdf
11M /home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI5.pdf
11M /home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI6.pdf
11M /home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI.pdf

My desire is that it prompts a user input as it reads every line.

8
  • Use a different FD at the outer read which is being done by the while loop. Commented Mar 24, 2021 at 19:30
  • 1
    while read -ru9 line; do ....; done 9< lista.txt Commented Mar 24, 2021 at 19:32
  • Thanks @Jetchisel it works to I'm learning bash at that -ru9 is new to me. Commented Mar 24, 2021 at 20:04
  • see help read Commented Mar 24, 2021 at 20:45
  • 1
    See the redirection section from man bash Commented Mar 24, 2021 at 22:24

1 Answer 1

1

The line you need to change is :

read -r -p "${1:-Usunąć podany plik? [t/N]} " response < /dev/tty
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Philippe that does the trick for me! Now I wonder what's the diffrence because when I'm trigering function alone it asks for input without that addon.
When you trigger function alone, read get inputs from standard input which is the same as /dev/tty. But when you put prompt inside while loop, prompt.read is also reading from the file. That's why you need to tell it to read from terminal, which is /dev/tty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.