Course contentsShow
← Linux
Lesson 153 of 1,8192. Deep Dive into Bash ScriptingFree lesson

File Descriptor Management

Open, close, and reassign custom file descriptors for advanced I/O.

In this lesson, you will learn how to manually open, close, and reassign custom file descriptors to gain fine-grained control over where your script sends its data.

Beyond Standard Streams

You are already familiar with the "big three" file descriptors: 0 (stdin), 1 (stdout), and 2 (stderr). However, Bash allows you to use file descriptors ranging from 3 to 9 for your own custom purposes. This is incredibly useful when you need to redirect logs to multiple files simultaneously or keep a file open for writing while your script performs other tasks.

Opening and Closing

To open a file for a custom descriptor, we use the exec command. Think of exec here not as a way to replace the shell, but as a way to manage the shell's internal "filing cabinet."

# Open 'log.txt' for writing on file descriptor 3
exec 3> log.txt

# Now, anything redirected to &3 goes into log.txt
echo "This is a custom log entry" >&3

# Close the file descriptor when finished
exec 3>&-

The syntax 3> filename tells the shell: "Open this file and assign it to slot 3." When you are done, 3>&- effectively tells the shell to close that slot, releasing the file handle.

Reassigning and Duplicating

You can also use these descriptors to perform complex redirection gymnastics. For example, if you want to redirect standard output to a file but keep the original terminal output available for later, you can "save" your current stdout to another descriptor first:

# Save current stdout (1) to descriptor 4
exec 4>&1

# Redirect stdout to a file
exec > output.log

echo "This goes to the file, not the screen."

# Restore stdout from 4 and close 4
exec 1>&4 4>&-

echo "Now we are back to talking to the terminal!"

By mastering these custom slots, you move from simple command redirection to building professional-grade scripts that handle complex data streams with precision and efficiency.

Key Takeaway: Use the exec command to assign files to custom descriptors (3-9) for flexible, persistent I/O control, and always close them using >&- to prevent resource leaks.