How to use a variable to indicate a file descriptor in bash?

WH's HeV picture WH's HeV · Nov 28, 2011 · Viewed 8.6k times · Source

I want to use a bash variable to indicate a file descriptor, like this:

id=6
file=a
exec $id<>$file

But the usage is wrong:

-bash: exec: 6: not found

So, how to use a variable to indicate a file descriptor in exec command?

Answer

Paul Tobias picture Paul Tobias · Sep 21, 2015

The accepted answer is correct, but as of bash 4.1, you can use automatic file descriptor allocation, and in that case you don't need eval:

file=a
exec {id}<>"$file"

Then you can use it like this:

echo  test >&${id}

or:

fsck -v -f -C ${id} /dev/something