This tutorial aims to teach you how to read from and write to files using redirection in shell scripts. Redirection is a powerful feature that allows data flow to be controlled. It enables the input and output of a program to come from and go to other programs or files.
By the end of this tutorial, you will be able to:
- Understand the concept of redirection in shell scripts
- Read from and write to files using redirection
- Apply best practices when using redirection
Prerequisites: Basic knowledge of shell scripting would be beneficial, but it's not mandatory.
In shell scripts, there are three standard streams: Standard Input (stdin), Standard Output (stdout), and Standard Error (stderr). By default, stdin reads input from the keyboard, stdout prints output to the screen, and stderr prints error messages to the screen. Redirection allows you to change these defaults.
Example:
echo "Hello, World!" > hello.txt
This command writes "Hello, World!" to the file hello.txt.
Example:
sort < file.txt
This command sorts the lines in file.txt.
Example:
echo "This is a new line" >> file.txt
This command adds "This is a new line" to the end of file.txt.
# This command writes "Hello, World!" to hello.txt
echo "Hello, World!" > hello.txt
# This command sorts the lines in file.txt
sort < file.txt
# This command adds "This is a new line" to the end of file.txt
echo "This is a new line" >> file.txt
In this tutorial, we covered the concept of redirection in shell scripts. We learned how to read from and write to files using the '<' and '>' operators, respectively, and how to append to a file using '>>'.
Next, you could learn about pipes, which is another powerful feature in shell scripting that works well with redirection.
Additional resources:
- Learn Shell
- Shell Scripting Tutorial
ls > dir.txt
This command writes the output of 'ls' to dir.txt.
Exercise 2: Write a command to append the current date to a file named date.txt.
date >> date.txt
This command adds the current date to the end of date.txt.
Exercise 3: Write a command to sort the lines in a file named unsorted.txt and write the sorted lines to a file named sorted.txt.
sort < unsorted.txt > sorted.txt
Practice these exercises and modify them to get a better understanding of redirection. Happy learning!