Saturnian
Saturnian

Reputation: 1938

How to read input inside a while loop while reading from a file?

I'm very new to bash scripting and here's what i'm trying to do:

1 - Read a file - this file is a list of names 2 - Ask user if they want to delete {name} 3 - If user enters y, proceed

This is what my script looks so far:

while IFS= read -r repo 
    do
        read -p "Do you want to delete $repo" ip 
        echo $ip
        if [ "$ip" == "y" ]
            then
            #do something
        fi

    done < "$filename"

The read -p line does not wait for a user prompt. I sort of understood what/where the problem is and I was trying to resolve it by reading up on this link - https://bash.cyberciti.biz/guide/Reads_from_the_file_descriptor_(fd)

But somehow I was unable to resolve this issue. What am I doing wrong? Please help!

Upvotes: 5

Views: 5533

Answers (2)

chepner
chepner

Reputation: 530853

Use a different file descriptor for the named file. You know where that data is coming from; you don't know where standard input might be redirected from, so leave it alone.

while IFS= read -r -u 3 repo   # Read from file descriptor 3
do
    read -p "Do you want to delete $repo" ip   # Read from whatever standard input happens to be
    echo "$ip"
    if [ "$ip" = "y" ]
    then
        #do something
    fi 
done 3< "$filename"  # Supply $filename on file descriptor 3

-u is bash-specific, but I note you are already using another bash-specific feature, the -p option to read. The POSIX way to read from something other than standard input is IFS= read -r repo <&3 (which says, copy file descriptor 3 onto standard input for this command).

Upvotes: 7

ACVM
ACVM

Reputation: 1527

See this question:

Does bash support doing a read nested within a read loop?

Essentially, you're reading in the file through standard input which is the same input stream as when you type, so when you prompt the user, the script is treating the file's input as the user's input. If you instead read in the the file on another input stream then it wouldn't override.

Upvotes: 3

Related Questions