3 File Descriptors in Unix Operating System: What They Mean

Unix operating system supports three file descriptors. Those are stdin(0), stdout(1) and stderr(2). Here is an example that shows how to use them.

File descriptor means standard file ports. Precisely, you can redirect your script command result or you can get input from terminal to script. Input & Output – These two functions you can do with the file descriptors.

File Descriptors

0 - stdin  - Keyboard
1 - stdout - display
2 - stderr - display

Details of File Descriptors

stdinStandard input
stdoutStandard output
stderrStandard error

What is a bit bucket in Unix?

It’s just a null file. It deletes data immediately after it receives, and sets the file status to end-of-file. Here is the directory of Bit Bucket.

Bit bucket

/dev/null

How to work with File Descriptors

Firstly, send error messages to stderr (2), then stderr(2) to stdout(1). The ‘>&’ just copy the messages present in stderr to stdout. The ‘$?’ tells the status of the previously executed command. Here is more on File Descriptors.

In myfunction1, added a command. I am checking the command status by using $?. After closing the curling bracket, I have given myfunction1 – why means this is how we call the function in the script.

#!/usr/bin/bash
myfunction1()
{
ls -0 > /dev/null 2>&1
echo "$?"
}
myfunction1

Video – How bit bucket discards Error Messages

The status code is ‘2’. That means only you will get status codes, and you’ll not get an error message, since it’s discarded.

Video – How to Display Error Messages

Modified Script

Here, I have used the local directory path, instead of the bit bucket directory. So you can see error messages and status codes as well.

#!/usr/bin/bash
myfunction1()
{
ls -0 > /tmp/dev/null 2>&1
echo "$?"
}
myfunction1

Related Posts

Get new content delivered directly to your inbox.

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.