Add text to a file, creating the file if it doesn’t already exist in Shell script

Shell Scripting @ Freshers.in

Manipulating file content is a routine task in Shell Scripting. This article demonstrates how to add text to a file, creating the file if it doesn’t already exist. This skill is particularly useful for logging, file modification, and simple data appending tasks.

Create a new script file:

Open a text editor like nano or vi to start a new script file. Type the following lines in the script:

#!/bin/bash
# Add text to hello.txt; create it if it doesn't exist
echo "Freshers.in!" >> hello.txt

Save and Close: In nano, save your script by pressing CTRL+X, then Y, followed by Enter.

Making the script executable

Change the script’s permissions to make it executable:

chmod +x textappend.sh

Run your script using:

./textappend.sh

To check if “Freshers.in!” has been added to ‘hello.txt’, use:

cat hello.txt

Read more on Shell and Linux related articles

Author: user