Skip to main content

Command Palette

Search for a command to run...

Creating a Bash Script to Check, Create, Append, and List Files

Published
2 min read

Bash scripting is a powerful way to automate tasks on Unix-based systems. In this blog post, I will guide you through creating a simple Bash script that checks if a file exists, creates the file if it doesn't, appends content to it, and lists all files in the current directory.

Step-by-Step Guide

  1. Open your terminal and create a new Bash script file. You can name it file_management.sh:

     touch file_management.sh
    
  2. Open the script in your preferred text editor:

     nano file_management.sh
    
  3. Add the following code to your script:

     #!/bin/bash
    
     # Define the file name
     FILENAME="example.txt"
    
     # Check if the file exists
     if [[ -e $FILENAME ]]; then
         echo "The file '$FILENAME' already exists."
     else
         # Create the file if it doesn't exist
         touch $FILENAME
         echo "The file '$FILENAME' has been created."
     fi
    
     # Append content to the file
     echo "Appending content to '$FILENAME'."
     echo "This is a new line of text." >> $FILENAME
    
     # List all files in the current directory
     echo "Listing all files in the current directory:"
     ls -l
    
  4. Save and exit the editor. In nano, you can do this by pressing CTRL + X, then Y, and finally Enter.

  5. Make the script executable by running the following command:

     chmod +x file_management.sh
    
  6. Run the script:

     ./file_management.sh
    

Explanation of the Script

  • Shebang (#!/bin/bash): This line tells the system to use the Bash shell to execute the script.

  • File Check: The script checks if example.txt exists using the -e flag. If it exists, a message is printed; if not, the file is created with touch.

  • Appending Content: The script appends a line of text to the file using the >> operator.

  • Listing Files: Finally, it lists all files in the current directory using the ls -l command.

Conclusion

This simple script demonstrates how to manage files using Bash. You can easily modify the script to suit your needs, whether it's changing the file name or the content being appended. Bash scripting can greatly enhance your productivity by automating repetitive tasks.

Feel free to experiment with this script and see how you can expand its functionality!


More from this blog

Amazon S3 Storage Classes

43 posts