Home > Blockchain >  bash script - while IFS causes program to hang
bash script - while IFS causes program to hang

Time:10-28

I've got a file (file1.txt) that looks like like

0,100,500
0,200,300
etc.

For each line, I need to run a program that will use some of this data as arguments.

Hence I wrote:

while IFS=',' read -r parameter1 parameter2 parameter3; do
/path/to/program/./program.bin -arg2 "$parameter2" -arg3 "$parameter3" 
done < file1.txt

When running the script, the program starts but it hangs and becomes totally unresponsive.

The funny thing is that when doing:

while IFS=',' read -r parameter1 parameter2 parameter3; do
echo /path/to/program/./program.bin -arg2 "$parameter2" -arg3 "$parameter3" >> commands.txt
done < file1.txt

and then

bash -i commands.txt

It works. The programs starts normally, finishes then runs again.

I don't have any background in IT and I don't understand what I'm doing wrong. Excuse me if the vocabulary I'm using isn't adequate.

CodePudding user response:

In general, if the body of your loop can read from some file descriptor (in this case, standard input), it's better to use a different file descriptor for your read command.

# Assuming program.bin does not read from file descriptor 3.
while IFS=',' read -r parameter1 parameter2 parameter3 <&3; do
    /path/to/program/./program.bin -arg2 "$parameter2" -arg3 "$parameter3" 
done 3< file1.txt

CodePudding user response:

Go see chepner's answer, it solves the problem in a more straightforward way.

Your program is very likely reading from standard input. Your file.txt is redirected to standard input, so both read and your program will try to read from the file. You have to force your program to read a different input or not read at all.

while IFS=',' read -r parameter1 parameter2 parameter3; do
  # /dev/null cannot be read from:
  /path/to/program/./program.bin -arg2 "$parameter2" -arg3 "$parameter3" </dev/null
done < file1.txt
while IFS=',' read -r parameter1 parameter2 parameter3; do
  # read user input from console:
  /path/to/program/./program.bin -arg2 "$parameter2" -arg3 "$parameter3" </dev/tty
done < file1.txt
while IFS=',' read -r parameter1 parameter2 parameter3; do
  # ":" builtin doesn't produce any output
  : | /path/to/program/./program.bin -arg2 "$parameter2" -arg3 "$parameter3"
done < file1.txt
  • Related