Size: 2013
Comment:
|
← Revision 7 as of 2023-04-08 22:38:46 ⇥
Size: 1883
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 29: | Line 29: |
Note that the `&` can be omitted from the source file descriptor. Also note that even though the redirection for `STDERR` followed the redirection to `STDOUT`, both streams are collated and redirected correctly. | Note that the `&` can be omitted from the source file descriptor. |
Line 63: | Line 63: |
Mostly only useful for [[Linux/Sockets|sockets]], but a bidirectional file descriptor can be opened like: | Mostly only useful for [[Linux/Networking#Unix_Sockets|sockets]], but a bidirectional file descriptor can be opened like: |
Bash File Descriptors
Contents
Standard File Descriptors
All shells inherit the 0th (STDIN), 1st (STDOUT), and 2nd (STDERR) file descriptors. File descriptors are referenced by their index and an ampersand (&) prefix.
File descriptors can be used with redirection.
The echo builtin normally outputs to STDOUT. To redirect that output to STDERR, try:
echo "Error!" >&2
Note that the STDOUT is redirected implicitly.
Alternatively, to combine the STDOUT and STDERR streams and redirect them to a file, try:
command example >/dev/null 2>&1
Note that the & can be omitted from the source file descriptor.
To read from STDIN, try:
while read line; do : done <&0
Non-standard File Descriptors
Declaration
Non-standard file descriptors have to be opened before they can be accessed.
To open a file descriptor for writing, try:
exec 3> myfifo
To open a file descriptor for reading, try:
exec 3< /path/to/a/temp/file
Mostly only useful for sockets, but a bidirectional file descriptor can be opened like:
exec 3<> /dev/tcp/www.example.com/80
Usage
Non-standard file descriptors, once opened, are used exactly like a standard file descriptor.
To write to one, try:
echo "Debug message" >&3
To read from one, redirect the extra stream into STDIN. For example, to read from &3, try:
while read line; do : done 0<&3
Closing
An opened file descriptor must be closed. This is accomplished by either redirecting it to -, or by redirecting - into it.
exec 3>&- #or: exec 3<&-