Sometimes you may need to write to files while using bash shell or writing shell script. In this article, we will look at the different ways to write to file in bash. You can also use these commands to write to file in other Linux shells, since they are available in almost every Linux distribution.
How to Write to File in Bash
Here are the different ways to write to file in bash.
1. > redirection operator
> redirection operator allows you to write text to a file. It can be used to redirect the output of another command or script to a file.
Here is its syntax
output > file_path
Here are a couple of examples
echo "hello world" > /home/ubuntu/data.txt ./test_script.sh > /home/ubuntu/data.txt grep "test" /product/data > /home/ubuntu/data.txt
If the file does not exist at the specified path, a new file will be created. If the output is null or blank then your entire file will be blanked out. Also, if you do not specify the absolute path, then the above command will search or create the file in present working directory.
So be careful while using > redirection operator to write files. It overwrites the content of specified file, without asking for any confirmation.
Also read : How to Disable HTTP Strict Transport Security Policy in Apache
2. >> redirection operator
>> redirection operator allows you to append text to existing files. It can be used to redirect output from command or script to a file.
Here is its syntax
output >> file_path
Here are some examples
echo "hello world" >> /home/ubuntu/data.txt ./test_script.sh >> /home/ubuntu/data.txt grep "test" /product/data >> /home/ubuntu/data.txt
If the file does not exist at the specified path, a new file will be created. Also, if you do not specify the absolute path, then the above command will search or create the file in present working directory.
It does not overwrite the content of specified file, only appends to it.
Also read : How to Convert Callback to Promise in NodeJS
3. Write to File with tee command
Sometimes you may want to also see the output that is being written to a file. In such cases, use tee command. tee command writes to standard output as well as one or more files. You can also use tee command to write to file without redirect.
Here is its syntax
output | tee file(s)
Here are some examples
echo "hello world" | tee /home/ubuntu/data.txt ./test_script.sh | tee /home/ubuntu/data.txt grep "test" /product/data | tee /home/ubuntu/data.txt
Here is an example of writing to multiple files
echo "hello world" | tee /home/ubuntu/data.txt /home/user1/data.txt /home/user2/data.txt
In this article, we have learnt three ways to write to file in bash. > redirection operator is used to overwrite file with new content. >> redirection operator is used to append to existing file. tee command is used to write output to both standard input as well as one or more files.
Also read : How to Rsync between two servers without password