2

I have a small section of code that reads a file, $FUNCTION_FILE which contains a list of function names in the format:

func1
func2
func3

It will read a line, run the function, and repeat until the file is done. Here is a snippet:

while read line; do
    LINE_NUMBER=`expr $LINE_NUMBER + 1`
    echo "LINE_NUMBER=$LINE_NUMBER"

    $func
done <$FUNCTION_FILE

I've gotten into a situation where sometimes this section of code will stop reading the "$FUNCTION_FILE" before finishing and move on with the rest of the script. Sometimes it'll only read the first line and skip the rest, sometimes only the second line; I never see the "LINE_NUMBER=$LINE_NUMBER" message for the subsequent lines either.

Assuming that the file is correct, what are some things that could cause this issue I'm seeing?

3
  • Does any line contain exit?
    – choroba
    Jan 23, 2014 at 14:36
  • You're asking us to debug arbitrary code that we can't see? Anything at all could be happening, it depends on what the $func are. Please show us the actual functions you are running, there is no way we can help otherwise.
    – terdon
    Jan 23, 2014 at 14:47
  • Sorry for being so cryptic. I'm not in a position to divulge any of the actual code, I'm mostly trying to gather info about ways a script can manipulate the stdin (as the first answer suggests). Thanks for your time, I really do appreciate it.
    – julian
    Jan 23, 2014 at 18:42

1 Answer 1

4

Do any of your functions read from stdin (ex: the read command)? If so, that will slurp up the rest of the FUNCTION_FILE.

Change the while loop to use a different file descriptor:

line_num=0
while read -u3 line; do
    echo "LINE_NUMBER=$(( ++line_num ))"
    $func
done 3<"$function_file"

Get out of the habit of using ALL_CAPS_VARIABLES -- one day you'll accidentally use "PATH" and break your script.

1
  • Thanks for the suggestion, I'll look deeper and see if this is the case. Unfortunately, a lot of the conventions are victims of a supremely old and large codebase, but I really appreciate your advice and will make sure to adhere to it in my own endeavors.
    – julian
    Jan 23, 2014 at 18:42

Not the answer you're looking for? Browse other questions tagged .