Fundumentals

File Descriptors - Fundamentals

What are File Descriptors?

File descriptors are non-negative integers that represent open files or input/output channels in Unix-like systems. Every process starts with three standard file descriptors:

  • 0 = stdin (standard input)
  • 1 = stdout (standard output)
  • 2 = stderr (standard error)

Basic Redirection

# Redirect stdout to a file
echo "Hello" > output.txt        # Same as: echo "Hello" 1> output.txt

# Redirect stdin from a file
cat < input.txt                  # Same as: cat 0< input.txt

# Redirect stderr to a file
ls /nonexistent 2> errors.txt

# Append to a file instead of overwriting
echo "More text" >> output.txt

Testing File Descriptors

Use the -t test to check if a file descriptor is connected to a terminal:

# Check if stdout is a terminal
if [ -t 1 ]; then
    echo "Output is going to terminal"
else
    echo "Output is redirected/piped"
fi

# Check stdin
[ -t 0 ] && echo "Input is from terminal"

# Check stderr
[ -t 2 ] && echo "Errors go to terminal"

More on this in Detecting Output Destination in CLI Programs


Backlinks