Input, Output, and Redirection
Introduction
Welcome! In this lesson, we will explore Input, Output, and Redirection using Bash. Scripts can take input from your keyboard, other scripts, files, and more. Understanding how to effectively manage these input sources, as well as how to redirect output to files or other commands, is crucial in automating tasks, creating efficient workflows, and building powerful scripts. By the end of this lesson, you will be able to redirect output to a file, read a file line by line, and use the pipeline (|) operator to redirect command outputs.
Let's dive in and start with redirecting output.
Understanding stdin, stdout, and stderr
Bash uses the concepts of standard input (stdin), standard output (stdout), and standard error (stderr) to manage input and output streams.
Standard Input (stdin) is the default source of input for a command. It is usually your keyboard input, but you can also redirect input from a file or another command.
Standard Output (stdout) is the default destination of output for a command. This is usually your terminal screen, but you can also redirect it to a file or as input to another command.
Standard Error (stderr) is the default destination for error messages from a command. By default, errors are displayed on your terminal screen, but you can redirect them to a file or another output stream.
Redirecting Output to a File
In the previous lesson, we saw how to use the > operator to redirect the output of an echo command to a file instead of displaying the output to the terminal. The > command overwrites the contents of the file with the output of the command. We can append more content to an existing file without overwriting it, you can use the >> operator.
- The first
echocommand sends "This is the first line." to the standard output. - The
>redirects thestdoutfrom the terminal tooutput.txt, overwriting any content of the file. - The second
echocommand sends "This is the second line" tostdout. - The
>>operator redirects the standard output and appends this output to theoutput.txtfile.
Now, the output.txt file contains:
