0

I'm trying to loop through the contents of a file in zsh. In my loop I want to get user input. Going off of this answer for Bash, I'm attempting to do:

while read -u 10 line; do
  echo $line;
  # TODO read from stdin here, etc.
done 10<myfile.txt

However I get an error:

zsh: parse error near `10'

Referring to the 10 after the done. Obviously I'm not getting the file descriptor syntax right, but I'm having trouble figuring out the docs.

xdhmoore
  • 8,935
  • 11
  • 47
  • 90

1 Answers1

2

Use a file descriptor number less than 10. If you want to hard code file descriptor numbers, stick to the range 3-9 (plus 0-2 for stdin,out,err). When zsh needs file descriptors itself, it uses them in the 10+ range.

If you're even getting close to needing more than the 7 available hard coded file descriptors, you should really think about using variables to name them. Syntax like exec {myfd}<myfile.txt will open a file with zsh allocating a file descriptor greater than 10 and assigning it to $myfd.

Bourne shell syntax is not entirely unambiguous given file descriptors numbering 10 and over and even in bash, I'd advise against using them. I'm not entirely sure how bash avoids conflicts if it needs to open any for internal use - I guess it never needs to leave any open. This may look like a zsh limitation at first sight but is actually a sensible feature.

okapi
  • 1,340
  • 9
  • 17
  • Hey thanks, that's good to know. it sounds like from the docs that that particular use of `exec` doesn't replace the current shell? It's just sort of a placeholder to allow you to do the redirection? – xdhmoore Oct 23 '20 at 06:23
  • 1
    Correct, `exec` with redirections is the Bourne shell way to open and close redirections for the current shell. The dual use of `exec` isn't clever but is, I guess, typical of that era. – okapi Oct 23 '20 at 06:30