File Operations
Introduction to File Operations in Bash
Welcome! In this lesson, we will dive into essential file operations using Bash. File operations are tasks performed on files, such as creating, reading, writing, copying, and deleting them. These operations are fundamental for managing data and organizing information on a computer system. Shell scripting with Bash (Bourne Again SHell) provides a powerful and flexible way to automate and streamline file operations. By using simple commands, you can perform complex tasks efficiently, saving time and reducing the potential for human error. Bash scripting is especially useful for repetitive tasks, large-scale file management, and system administration.
Creating a File
Let's start by creating a new file.
The touch command creates an empty file if the given file name doesn't already exist. If the file does already exist, touch updates the file's last modified timestamp without changing its content. Let's create a file called example.txt.
The command creates a new file called example.txt in the current working directory (We will cover directories in more detail later in this course). If example.txt already exists, this command updates its last modified timestamp.
example.txt can now be opened and edited. In the practice exercises, you can open this file by clicking the ☰ icon to the right of Cosmo's message.
Writing to a File
Instead of opening the example.txt file manually and adding text, we can write to the file by using the > operator. The > operator in Bash is used for output redirection. It takes the output of a command and writes it to a specified file, overwriting the file's contents if it already exists. If the file does not exist, the > operator creates a new file with the specified name and writes the output to it. The basic syntax is:
We can write text to the example.txt file as follows:
The > operator directs the output of echo into example.txt, overwriting any existing content. Opening example.txt will show:
Displaying the Content of a File
