Bash – In Bash, what is file descriptor 255 for, can I use it

bashfile-descriptors

I understand file descriptor (or file handler) is an file IO technique in Linux systems.

I also know that each process has 3 standard streams (namely stdin, stdout and stderr) that are represented by files with descriptors from 0 to 3.

However, I notice that all the processes I examined with lsof -p <pid> has an extra file descriptor 255 with read permission.

From this answer, I learned that this feature is specific to Bash shell, however both the answer the and the referenced source didn't really explain what this file descriptor is for.

My question:

  1. What is the 255 file descriptor for?
  2. Can I make use of it in my Bash script or is it just an internal working mechanism that is not supposed to be used/manipulated manually?

Best Answer

For the last part of your question:

can I use it?

From man bash:

Redirections using file descriptors greater than 9 should be used with care, as they may conflict with file descriptors the shell uses internally.

So, if you mean use as creating a new fd with that number the answer is no.

If you mean use as: "write to that fd":

$ echo hello >/dev/fd/255"

Or to read from it:

$ read a </dev/fd/255
abc
$ echo "$a"
abc

the answer is yes.
But, probably, it should be better (independent of shell) to use /dev/tty to access the tty.

what is file descriptor 255 for?

As an alternative connection to the tty in case fd 1 (/dev/stdout) and fd 0 (/dev/stdin) get blocked.

More detail.

Other shells may use a different number (like 10 in zsh)

$ zsh
mail% ls -l /proc/self/fd /proc/$$/fd/* &
[1] 3345
mail% lrwx------ 1 isaac isaac 64 Oct 14 09:46 /proc/3250/fd/0 -> /dev/pts/2
lrwx------ 1 isaac isaac 64 Oct 14 09:50 /proc/3250/fd/1 -> /dev/pts/2
lrwx------ 1 isaac isaac 64 Oct 14 09:50 /proc/3250/fd/10 -> /dev/pts/2
lrwx------ 1 isaac isaac 64 Oct 14 09:50 /proc/3250/fd/2 -> /dev/pts/2

/proc/self/fd:
total 0
lrwx------ 1 isaac isaac 64 Oct 14 09:50 0 -> /dev/pts/2
lrwx------ 1 isaac isaac 64 Oct 14 09:50 1 -> /dev/pts/2
lrwx------ 1 isaac isaac 64 Oct 14 09:50 2 -> /dev/pts/2
lr-x------ 1 isaac isaac 64 Oct 14 09:50 3 -> /proc/3345/fd

[1]  + done       ls -l /proc/self/fd /proc/$$/fd/*
mail% 

From mail list:

Fd 255 is used internally as a connection to the tty, so that it doesn't interfere with the use of exec to relocate fds. Bash also allocates high fds when handling a process substitution `<(foo)', for the same reason.
Andreas Schwab

Related Question