Reading from a file and creating it if it doesn’t exist using Shell script

Shell Scripting @

We’ll delve into a common yet essential task in Shell Scripting: reading from a file and creating it if it doesn’t exist.

Creating a New Script File:

Open a text editor (like nano or vi) and create a new file:

Script Content:

Input the following lines into the script:

# Check if the file exists
if [ -f "$FILE" ]; then
    echo "Reading from $FILE:"
    cat $FILE
    echo "$FILE does not exist. Creating the file."
    touch $FILE

Save and Exit: Save the script and exit the text editor. In nano, this is done with CTRL+X, then Y, and finally Enter.

Step 3: Making the Script Executable

Change your script’s permissions to make it executable:

chmod +x

Execute the script with:


Read more on Shell and Linux related articles

Author: user