Redirecting Input and Output

Redirecting Input and Output

Redirecting input and output is a powerful feature of the shell that allows you to control where input comes from and where output goes to. This is done using special characters, known as redirection operators, which are placed between the command and the file or device that you want to redirect input or output to.

Redirecting Output

To redirect the output of a command to a file, use the > operator. For example, the following command redirects the output of the ls command to a file called filelist.txt:

ls > filelist.txt 

If the filelist.txt file already exists, it will be overwritten. To append the output of a command to a file instead of overwriting it, use the >> operator:

ls >> filelist.txt 

This will append the output of the ls command to the end of the filelist.txt file.


Redirecting Input

To redirect the input of a command from a file, use the < operator. For example, the following command uses the cat command to display the contents of a file called myfile.txt:

cat < myfile.txt 


Pipes

Pipes are another way of redirecting output. A pipe is a vertical bar | that connects two commands. The output of the first command is piped (i.e., redirected) to the input of the second command. This allows you to chain together multiple commands to perform more complex operations.

For example, the following command lists all the files in the current directory and pipes the output to the grep command, which searches for files that contain the word "example":

ls | grep example 


/dev/null

Another useful device that can be used for redirection is /dev/null. This device is essentially a black hole that can be used to discard unwanted output. For example, the following command runs a command and discards its output:

command > /dev/null 


This is useful if you want to run a command but don't want to see any output.

Complete and Continue