Skip to main content

Bash Script File Handling

Bash scripting is a powerful tool for handling file operations. Whether it's automating mundane tasks or orchestrating complex workflows, understanding how to handle files in Bash scripts is invaluable. Let's dive into this essential skill.

What is Bash Scripting?

Bash scripting is a way to automate tasks using the command line interpreter of Unix-based systems. It allows you to write commands in a file to run them as a program. This simplicity transforms repetitive tasks into single-click operations and elevates productivity.

How to Create and Run a Bash Script

Creating a Bash script is straightforward. Open a terminal, use your preferred text editor, and create a new .sh file. Here’s a quick example of how to turn a few commands into a Bash script:

  1. Create the Script:

    nano my_script.sh
    
  2. Add the Shebang: Start with #!/bin/bash to indicate the script's interpreter.

  3. Write Commands:

    #!/bin/bash
    echo "Hello, World!"
    
  4. Make it Executable:

    chmod +x my_script.sh
    
  5. Run the Script:

    ./my_script.sh
    

Briefly, the shebang (#!) tells the system that this file should be executed using Bash. By running chmod +x, we make the script executable.

File Handling Operations

Handling files in Bash involves creating, reading, writing, and deleting files. Here's how each operation is done:

Creating Files

Creating a file in Bash can be done with the touch command:

touch newfile.txt

This command creates an empty file named newfile.txt.

Writing to Files

You can use the echo command to write to a file. Use the > operator to overwrite a file or >> to append to it:

echo "This is a line of text." > newfile.txt
echo "This text comes next." >> newfile.txt

Here, > creates and writes to newfile.txt. If the file exists, it overwrites it. >> appends to the existing content.

Reading Files

To read file content, use the cat, less, or more commands:

cat newfile.txt

cat will display the entire file content, while less and more allow for scrolling through the content, which is useful for longer files.

Deleting Files

Remove files with the rm command:

rm newfile.txt

Use this cautiously as it deletes files permanently.

Managing Directories

File handling isn't complete without managing directories. Here's how you can work with directories in Bash:

Creating Directories

Use mkdir to create a new directory:

mkdir new_directory

Create multiple nested directories with the -p option:

mkdir -p parent/child/grandchild

Moving and Renaming Files

Utilize mv to move or rename files:

mv oldfile.txt newfile.txt
mv newfile.txt new_directory/

The first command renames oldfile.txt to newfile.txt. The second moves it into new_directory.

Copying Files

The cp command copies files or directories:

cp file.txt newfile.txt
cp -r source_directory/ target_directory/

-r ensures the entire directory, with all files and subdirectories, is copied.

File Permissions

File permissions are crucial for security and file management in Bash scripts. Use chmod to change file permissions:

chmod 644 newfile.txt
chmod +x script.sh

Permissions are given in a three-digit format, representing read, write, and execute permissions for the owner, group, and others.

Conclusion

Mastering file handling in Bash scripts opens doors to automating a wide array of tasks. From simple file creation to complex directory management, Bash can significantly reduce the manual effort involved in day-to-day operations.

Unleash the potential of Bash, and see how your productivity soars.

Popular posts from this blog

C++ vcpkg Manifest Mode + CMake

 If you've ever tried to install a C++ library and felt like you were assembling furniture without instructions, this article is for you. We're going to talk about vcpkg manifest mode and how it works with CMake , and I'm going to explain it like you're five years old (in a good way — no judgment here). First, Let's Talk About the Problem In most programming languages, adding a library is easy. Python has pip install requests . JavaScript has npm install express . You type one command, and boom, the library shows up in your project. C++ never really had that. For decades, if you wanted to use a library like fmt or nlohmann/json , you had to: Download the source code yourself Figure out how to compile it Tell your compiler where to find the headers Tell your linker where to find the compiled binaries Cry a little vcpkg is Microsoft's answer to this mess. It's a package manager for C++ — like pip or npm , but for C++ libraries. And manifest mode...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...