readarray keyword stop value

535 views Asked by At

My goal is to read user input into an array for later use in the bash script. It works insofar as taking the users input and putting it into an array, but only if the user knows to press CTRL+D to terminate the readarray command.

Is there a away to tell read array to stop reading lines of input once it hits a specific keyword like "done" or "end"?

I've tried looking up ways to terminate the command, but am new to bash, so I am not sure if this is possible with a while/for loop, such as:

echo Type 'done' when finished
while true
do
    readarray -t serverlist

if [ "$LINE" = "done" ]
then
    false
fi
done
1

There are 1 answers

1
chepner On BEST ANSWER

readarray is going to read all of its standard input, including any sentinel like done or end before you have a chance to test it. You'll have to read the input line by line with read, and append each appropriate line to the array yourself.

echo 'Print "done" when finished'
while IFS= read -r line; do
    [[ $line = done ]] && break
    serverlist+=("$line")
done