Course contentsShow
← Linux
Lesson 48 of 1,8191. Shell Architecture and Process EnvironmentFree lesson

File Descriptor Cloning

Duplicate file descriptors to perform complex redirection sequences in shell scripts.

In this lesson, you will learn how to create "backup copies" of your file descriptors to perform complex, multi-stage input/output redirections in your shell scripts.

The Concept of Duplication

By default, every process starts with three standard streams: 0 (stdin), 1 (stdout), and 2 (stderr). Sometimes, you need to temporarily redirect output to a file, but you still want to preserve the original destination (like the terminal) so you can send data back there later. This is where File Descriptor (FD) Cloning comes in.

In shell syntax, we use the >& operator to duplicate an output FD or <& to duplicate an input FD. Think of this as creating a bridge; you are telling the shell, "Take this target FD and make it point exactly where the source FD is currently pointing."

A Practical Example

Imagine you want to run a command, save its output to a log file, but also keep the ability to print "Status: Done" directly to your terminal. Here is how you clone your stdout:

# 1. Clone stdout (1) to a new FD, say, 3. 
# Now, 3 is a "backup" of the terminal.
exec 3>&1

# 2. Redirect stdout (1) to a file.
exec > output.log

# 3. Everything now goes to the log file.
echo "This is logged to the file."

# 4. Use the clone (3) to send data back to the terminal.
echo "This goes to the terminal!" >&3

# 5. Clean up by closing the cloned FD.
exec 3>&-

Why Do We Use exec?

When used with redirections, exec tells the shell to apply these changes to the entire current shell environment rather than just for a single command. By cloning stdout to 3, you create a persistent alias for the original output stream. This allows you to juggle multiple output destinations without losing track of your original "home" terminal.

If you skip cloning, once you redirect stdout to a file, the terminal is essentially "lost" to that process until you manually restore it by pointing 1 back to the original source. Cloning gives you the flexibility to move back and forth between different I/O targets.

Key Takeaway: File descriptor cloning allows you to create persistent aliases for I/O streams, enabling you to redirect output to files while retaining a "backup" handle to return output to the original terminal.