0
0
Bash Scriptingscripting~5 mins

File descriptors and redirection in Bash Scripting

Choose your learning style9 modes available
Introduction

File descriptors let your script control where input comes from and where output goes. Redirection sends output to files or reads input from files instead of the screen or keyboard.

Save the output of a command to a file instead of showing it on the screen.
Read input for a command from a file instead of typing it manually.
Send error messages to a separate file to keep logs clean.
Combine output and error messages into one file for easier debugging.
Ignore output or errors when you don't need to see them.
Syntax
Bash Scripting
command > file       # Redirect standard output (stdout) to a file
command < file       # Redirect standard input (stdin) from a file
command 2> file      # Redirect standard error (stderr) to a file
command >> file      # Append standard output to a file
command &> file      # Redirect both stdout and stderr to a file

File descriptor 0 is standard input (stdin).

File descriptor 1 is standard output (stdout), and 2 is standard error (stderr).

Examples
Saves the list of files in the current folder to files.txt instead of showing it on the screen.
Bash Scripting
ls > files.txt
Reads the content of unsorted.txt as input to the sort command.
Bash Scripting
sort < unsorted.txt
Searches for 'error' in logfile.txt and sends any error messages to errors.txt.
Bash Scripting
grep 'error' logfile.txt 2> errors.txt
Adds the word 'Hello' to the end of greetings.txt without deleting existing content.
Bash Scripting
echo 'Hello' >> greetings.txt
Sample Program

This script runs ls commands and redirects outputs and errors to different files. Then it shows what was saved in those files.

Bash Scripting
#!/bin/bash

# Redirect output to a file
ls > output.txt

# Redirect errors to a file
ls non_existing_file 2> error.txt

# Redirect both output and errors to one file
ls existing_file non_existing_file &> combined.txt

# Show contents of the files
cat output.txt
cat error.txt
cat combined.txt
OutputSuccess
Important Notes

Use >> to add to a file without erasing it.

Use > to redirect only standard output, and 2> for standard error.

&> redirects both output and error together.

Summary

File descriptors 0, 1, and 2 represent input, output, and error streams.

Redirection changes where commands get input or send output.

Use redirection to save outputs, handle errors, or combine both.