Create a text file named books.txt with the following content to do the examples shown in the next part of this article.
books.txt:
Learning Laravel
Web Design using HTML
Example-1: Append line to the file using ‘echo’ command and ‘>>’ symbol
In the following script, an existing file, books.txt is assigned to the variable, filename, and a string value will be taken as input from the user to add at the end of the file. If the input value is not empty, then the ‘echo’ command will append the value into the books.txt file by using ‘>>’ symbol.
# Define the filename
filename='books.txt'
# Type the text that you want to append
read -p "Enter the text that you want to append:" newtext
# Check the new text is empty or not
if [ "$newtext" != "" ]; then
# Append the text by using '>>' symbol
echo $newtext >> $filename
fi
Output:
‘Learning JQuery‘ is taken as a new text value in the output that is appended at the end of the file.
Example-2: Append line to the file using ‘printf’ command and ‘>>’ symbol
‘>>’ symbol can be used with the ‘printf’ command to append formatted content to a file. Like the previous example, the filename and the string values are assigned to the variables, filename, and newtext. Next, ‘printf’ command will redirect the value of newtext with other text into the end of the books.txt file.
# Define the filename
filename='books.txt'
# Type the text that you want to append
read -p "Enter the text that you want to append:" newtext
# Check the new text is empty or not
if [ "$newtext" != "" ]; then
# Append the text by using '>>' symbol
printf "Appended text is: %s\n" "$newtext" >> $filename
fi
Output:
‘Website by WordPress‘ is taken as a new text value in the output that is appended at the end of the file.
Example-3: Append line to the file using `tee` command
‘tee’ is another useful command to append any string into a file. In the following script, the filename and the new text values are assigned like the previous examples. If the text value is not empty, then the ‘echo’ command will send the value to the ‘tee’ command using ‘|’ symbol. ‘-a’ option is used with ‘tee’ command here to append the received input value to the file books.txt. ‘/dev/null’ is used in the script to prevent showing the output in the terminal.
# Define the filename
filename='books.txt'
# Type the text that you want to append
read -p "Enter the text that you want to append:" newtext
# Check the new text is empty or not
if [ $newtext != "" ]; then
# Append the text by using `tee` command
echo $newtext | tee -a $filename > /dev/null
fi
Output:
‘Learning CSS3‘ is taken as a new text value in the output that is appended at the end of the file.
Conclusion:
Three different ways are shown in this article to append text at the end of a file using a bash script.