3

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!

Saturnian
  • 1,686
  • 6
  • 39
  • 65

2 Answers2

5

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).

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thank you so much! I totally missed the "3" part! I then defined it in the beginning as `exec 3< $filename` and it worked! :) – Saturnian Sep 22 '17 at 22:21
  • 1
    I would keep the redirection on the loop, if there is no need to keep the file open longer. – chepner Sep 22 '17 at 23:09
2

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.

ACVM
  • 1,497
  • 8
  • 14