jessarah
jessarah

Reputation: 351

bash syntax error "exec 11<<&-"

Hi I have a bash scripts that's throwing an error:

scriptx.sh: line 276: syntax error near unexpected token `&'

The error is on last line of this snippet:

find * -type f > $loopfile
exec 11<$loopfile
while read file; do
  # Here some process....
  :
done
exec 11<<&-

What is the purpose of:

exec 11<$loopfile
exec 11<<&-

Thanks.

Upvotes: 1

Views: 209

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 80931

Two sections from the bash man page are relevant here.

Redirecting Input

Redirection of input causes the file whose name results from the expansion of word to be opened for reading on file descriptor n, or the standard input (file descriptor 0) if n is not specified.

   The general format for redirecting input is:

          [n]<word

and

Duplicating File Descriptors

The redirection operator

   [n]<&word

is used to duplicate input file descriptors. If word expands to one or more digits, the file descriptor denoted by n is made to be a copy of that file descriptor. If the digits in word do not specify a file descriptor open for input, a redirection error occurs. If word evaluates to -, file descriptor n is closed. If n is not specified, the standard input (file descriptor 0) is used.

So the first line exec 11<$loopfile opens up file descriptor 11 to be opened for reading input and the input is set to come from $loopfile.

The second line exec 11<<&- then closes the (opened by the first line) descriptor 11... or rather it would were it not for the syntax error that chepner notes that I glossed over in my initial reading. The correct line should be exec 11<&- to close the fd.

To answer the follow-up question asked within the OP's self-answer unless this script uses fd 11 in that loop somewhere these lines seem to have no purpose. I would have normally assumed that this would be being done for use by read in that loop but that would require -u 11 (and could as easily be done with while read file; do ... done <$loopfile).

Upvotes: 2

jessarah
jessarah

Reputation: 351

The error is thrown because to close a file descriptor it requires only one redirection operator 11<&- and the script had two: 11<<&-

A code sample on how to use it:

exec 11<$loopfile  # File descriptor 11 is made copy of $loopfile
while read -u 11 file; do
   : # process
done
exec 11<&-          # File descriptor 11 is closed.

What is the advantage of duplicating the file descriptor?

Upvotes: 0

Related Questions