Reading and writing to files are common tasks among Linux command-line users. There are two ways in bash you can use to write to files including the redirection operator (
>) and the tee command. You need to have write permission in order to input any data into a file, otherwise, you will end up with a permission denied error.
In this article, we will discuss the bash write to file operation using the redirection operator and tee command for example.
Write to File using Redirection Operators
There are two ways to write data into a file using the redirection operator:
>operator overwrites the existing data within the file.
>>operator appends data into the file.
The general syntax of the redirection operator is:
data > file_name
data >> file_name
> Redirection Operator
> redirection operator writes data into the given file. If the file does not exist, then it creates a new file and writes the data and if the file already exists, it’s truncated to the length of zero and the data is written.
In the following example, we will redirect the output of the echo command to file.txt:
echo "Line 1 of file.txt" > file.txt
You can use the
noclobber option before using the redirection operator to prevent overwriting. This will return an output saying cannot overwrite existing file.
set -o noclobber echo "Line 1 of file.txt" > file.txt
To overwrite the
noclobber option, replace the
> redirection operator with
>> Redirection Operator
To redirect text into a file without overwriting, you can use the
>> redirection operator. It appends data into an existing file without overwriting its content.
In the following example, we will write data from the
echo command into file.txt:
echo "This is a line in file.txt" >> file.txt
Write to File using the tee Command
The tee command works similar to the redirection operators as it reads from the standard input and writes to standard output and files.
However, it can write data to more than one file simultaneously.
echo "output of the echo command" | tee file1.txt file2.txt
By default, the
tee command works the same as the
> redirection operator as it also overwrites files. To avoid that and append data at the file, use the
--append) option with the command:
echo "output of the echo command" | tee -a file.txt
We have covered the most common ways to write data into a file in this article. We hope you find this useful, but be sure to practice and explore how the commands and operators work in bash. If you encounter any issues, or have any questions/feedback, then feel free to let us know in the comments below.