bashstdin

Asking for user input in a while loop in a bash script


I am running on Ubuntu 24.04. I created a bash script that reads a file line by line in a loop and asks in this loop for a user input. (In fact it calls a function where this happens and something more, but to simplify my problem, we can ignore that) Here is a simpel version of my script:

#!/bin/bash

REMOTE_CONFIG_LIST="./files_to_copy.txt"

while IFS=' ' read -r remote_file local_dest
do
        echo
        echo "Line = " "$remote_file" "$local_dest"
        read -p "Please enter your name: " name
        echo "Hello, $name!"
        echo

done < "$REMOTE_CONFIG_LIST"

I understand that the reason for a failure of that script is the fact that the first read is not finished while I start the 2nd read. What are my options here ?

Thanks in advance and best regards

Daniel

Actual result: Line = /home/azureconf/conf/ubuntu/05-sentinelconnector.conf /etc/rsyslog.d Hello, /home/azureconf/conf/ubuntu/rsyslog.conf /etc!

Expected result: Line = /home/azureconf/conf/ubuntu/05-sentinelconnector.conf /etc/rsyslog.d Please enter your name: Daniel Hello, Daniel

Line = /home/azureconf/conf/ubuntu/rsyslog.conf /etc Please enter your name: Daniel Hello, Daniel


Solution

  • Use a dedicated file descriptor:

    Under bash, you could generate temporary unnamed fifo, then link them do a free file descriptor and store his value into a variable by simply: {varname}< syntax:

    #!/bin/bash
    
    REMOTE_CONFIG_LIST="./files_to_copy.txt"
    
    while IFS=' ' read -ru $CONFIG remote_file local_dest; do
        echo
        echo "Line = " "$remote_file" "$local_dest"
        read -p "Please enter your name: " name
        echo "Hello, $name!"
        echo
    done  {CONFIG}< "$REMOTE_CONFIG_LIST"