Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

The bash read command is very convenient for:

  • read -p to prompt the user and capture input from the user
  • while read loop to iterate through the lines of a file.

However, I'm having issues attempting to do both simultaneously.

For example:

#!/bin/bash  while read item do      echo Item: $item      read -p "choose wisely: " choice      echo You still have made a $choice.  done < /tmp/item.list  

Rather than blocking and standing by for the user to enter a choice, bash is populating $choice with the next item in the item.list file.

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

like image 396
ddoxey Avatar asked Apr 30 '13 20:04

ddoxey


People also ask

Does bash support nested loops?

Nested loop definition That is to say, it is a loop that exists inside an outer loop. When you integrate nested loops in bash scripting, you are trying to make a command run inside another command. This is what it means: a bash nested for loop statement runs a command within another loop.

How does read work in bash script?

Bash read SyntaxThe read command takes the user input and splits the string into fields, assigning each new word to an argument. If there are fewer variables than words, read stores the remaining terms into the final variable. Specifying the argument names is optional.

What is read line in bash?

The Readline library gives you a set of commands for manipulating the text as you type it in, allowing you to just fix your typo, and not forcing you to retype the majority of the line.


1 Answers

The simplest fix is to have the outer read read from a different file descriptor instead of standard input. In Bash, the -u option make that a little easier.

while read -u 3 item do   # other stuff   read -p "choose wisely: " choice   # other stuff done 3< /tmp/item.list 
like image 169
Zombo Avatar answered Sep 22 '22 02:09

Zombo