DEV Community

Dharamraj Yadav
Dharamraj Yadav

Posted on

Understanding File Descriptors & Redirection in Linux

File Descriptors

What is a File Descriptors

A file descriptor is simply a non-negative integer that the opreting system uses to identify an open file or I/O resources. in linux eveything is treating as a file, including a regular file, pipes, sockets, and devices. Every process starts with three standard file descriptor.

  • 0 – stdin (standard input)

  • 1 – stdout (standard output)

  • 2 – stderr (standard error)

Redirection in Linux

>

single greater-than (>) redirection in linux used to overwrite the file. for example:-

echo "Hello" > file.txt
Enter fullscreen mode Exit fullscreen mode

>>

double greater-than (>>) used to append in the file. for example:-

echo "My Name is Dharam" >> file.txt
Enter fullscreen mode Exit fullscreen mode

<

less-than use to input from a file. for example:-

wc -c < file.txt
Enter fullscreen mode Exit fullscreen mode

2>

redirect error to a file

ls -la not-exist-file.txt 2> error.log
Enter fullscreen mode Exit fullscreen mode

2>&1

redirect error and without error output

ls -l file.txt test.txt > output.txt 2>&1
Enter fullscreen mode Exit fullscreen mode

&> and &>>

sort version of 2>&1, this redirection also use to output and error.

tee

tee command used to view and redirect output.

ls -l testfile.txt | tee output.txt
Enter fullscreen mode Exit fullscreen mode

| - Pipe

Pipe (|): Sends the output of one command directly as the input to another command.

Top comments (0)