'Can't use named file descriptor in bash script: "exec: {foo}: not found"

My script file, foo.sh:

#!/bin/bash
exec {foo}>foo.txt
echo "test" >&$foo
exec {foo}>&-

Run it:

$ ./foo.sh
./foo.sh: line 2: exec: {foo}: not found

Why am I getting that error?

$ bash --version
GNU bash, version 5.1.4(1)-release (x86_64-apple-darwin18.7.0)
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

From man bash locally:

Each  redirection  that  may be preceded by a file descriptor number may instead be preceded by a word of the form {varname}.  In this case, for each redirection
operator except >&- and <&-, the shell will allocate a file descriptor greater than or equal to 10 and assign it to varname.  If >&- or <&- is preceded by  {var-
name},  the  value of varname defines the file descriptor to close.  If {varname} is supplied, the redirection persists beyond the scope of the command, allowing
the shell programmer to manage the file descriptor himself.


Solution 1:[1]

I have different versions of Bash on my system.

$ which bash
/usr/local/bin/bash
$ /usr/local/bin/bash --version
GNU bash, version 5.1.4(1)-release (x86_64-apple-darwin18.7.0)
...
$ /bin/bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin20)
...

I changed the shebang to #!/usr/local/bin/bash and the named file descriptor worked.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt Miller