Bash – Append text to file

To append a text to existing file in Bash scripting, you can use echo command with >>. Specify text and path to file in the command as shown in the following.

</>
Copy
echo "Your text here" >> /path/to/file

If the file is not present, you may create the file with specified file path and append the text to file using the following command.

</>
Copy
echo "Your text here" > /path/to/file

Please notice the difference between the above two commands. The first has >> and the second has >.

Example

In the following script, we take a string in str and file path in file_path. We check if file exists and if it exists, we append the text in str to the file. If the file does not exist, we create a file at specified path and then append the text to the file.

sample.txt – File contents

Bash - Append a text to file

example.sh

</>
Copy
#!/bin/bash

file_path="sample.txt"
str="This is a new line in the file.\n"

# Check if the file exists
if [ -f "$file_path" ]; then
  # Append text to the file
  echo "$str" >> "$file_path"
  echo "String appended to file."
else
  # If the file doesn't exist, create it and add the text
  echo "$str" > "$file_path"
  echo "File created, and string appended to file."
fi

Bash Version: GNU bash, version 5.2.15(1)-release (aarch64-apple-darwin22.1.0)

Output

sh-3.2# bash example.sh 
String appended to file.

sample.txt – File contains after appending text to file

Bash - After appending text to file

References

Bash If Else

Conclusion

In this Bash Tutorial, we learned how to append text to file using echo command.