Using exec to assign a file descriptor (fd) to file

In the Bash shell environment, every process has three files opened by default. These are standard input, display, and error. The file descriptors associated with them are 0, 1, and 2 respectively. In the Bash shell, we can assign the file descriptor to any input or output file. These are called file descriptors.

The syntax for declaring output.txt as output is as follows:

    exec fd > output.txt
  

This command will declare the number fd as an output file descriptor.

The syntax for closing the file is as follows:

    exec fd<&-
  

To close fd, which is 5, enter the following:

    exec 5<&-
  

We will try to understand these concepts by writing scripts.

Get Learning Linux Shell Scripting - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.