Module lessons (1/2)
Output and redirects (echo, cat, >)
In Linux, almost all commands read data from an input stream and write results to an output stream. These channels are called standard streams:
- Standard Input (stdin): The stream from which the command reads its input (default is the keyboard).
- Standard Output (stdout): The stream to which the command writes its successful output (default is the terminal screen).
- Standard Error (stderr): The stream to which the command writes its error messages (default is the screen).
Using the command line, we can redirect these streams to save results directly into files.
Printing Text: echo
The echo command simply writes its arguments to its standard output (the screen):
echo "Hello everyone"Redirecting Output (Overwrite): >
If you want to save the output of a command to a file instead of displaying it on the screen, you can use the greater-than redirect operator >:
echo "Hello everyone" > greetings.txtThis command runs echo and redirects its output to the file greetings.txt.
[!IMPORTANT] If the file
greetings.txtdoes not exist, it is created. If it already exists, its existing content is completely deleted and overwritten with the new output.
Reading File Contents: cat
To view the content of one or more text files on the fly, use the cat command (short for concatenate):
cat greetings.txtAppending Output: >>
If you want to append new lines to the end of an existing file rather than overwriting it, you must use the append operator >>:
echo "New line of text" >> greetings.txtNow, reading the file with cat greetings.txt will show both the first line and the second line.
Usage Examples and Common Errors
You can pass multiple files to cat at the same time to display them sequentially (concatenated):
cat notes.txt info.txt
# Output:
# Keep learning Linux!
# Linux is awesome.You can redirect the combined output to a third file using the > operator:
cat notes.txt info.txt > combined.txtIf you try to read a file that does not exist, cat will write an error message:
cat nonexistent_file.txt
# Output:
# cat: nonexistent_file.txt: No such file or directoryTry it yourself
Exercise 1: Create a file with a greeting
Create a file named 'hello.txt' containing exactly the text 'Hello World' using echo and the > operator.
Show hint
Use echo followed by the string in quotes, the > operator, and hello.txt.
Solution available after 3 attempts
Exercise 2: Append notes to a file
Append the line 'Linux is fun' to the end of the existing 'notes.txt' file without deleting its current contents.
Show hint
Use the >> operator to append text to the notes.txt file.
Solution available after 3 attempts
Exercise 3: Concatenate files
Concatenate the contents of the files 'notes.txt' and 'info.txt' and save the combined output to a new file named 'combined.txt'.
Show hint
Use cat followed by the names of the two source files and redirect the output with > to the destination file.
Solution available after 3 attempts