Creating Files with Bash Scripting: For Loop and If Test

Creating Files with Bash Scripting: For Loop and If Test

Welcome to the world of Bash scripting! In this article, we will delve into the intricacies of creating files with Bash scripting using for loops and if tests. You will discover the power and flexibility of Bash scripting as we explore how to automate tasks and manipulate files efficiently.

Get ready to unlock the potential of your scripts and optimize your workflow with the skills you’ll gain from this guide.

Creating a Bash Script using For Loop and If Test

Let’s create a Bash script that uses a for loop and an if test to achieve your goal. I’ll provide you with an example script that finds lines containing the name “jane” in a file and stores those filenames in another text file called oldFiles.txt.

#!/bin/bash

# Create an empty oldFiles.txt
> oldFiles.txt

# Find filenames containing "jane" in ../data/list.txt
files=$(grep "jane" ../data/list.txt | cut -d ' ' -f 3)

# Iterate over the filenames
for i in $files; do
    # Check if the file exists
    if test -e ~/data/"$i"; then
        echo "$i" >> oldFiles.txt
    else
        echo "File doesn't exist"
    fi
done

Here’s what the script does step by step:

  1. It initializes an empty oldFiles.txt.
  2. Searches for lines containing “jane” in ../data/list.txt.
  3. Extracts the filenames from the third column.
  4. Checks if each filename exists in the file system.
  5. If the file exists, it appends the filename to oldFiles.txt.

Understanding the Shebang in Bash Scripts

The shebang (also known as a hashbang or interpreter directive) is a crucial line in a Bash script. It specifies which interpreter should be used to execute the script. Let’s dive into the details:

  1. What is the Shebang?

    • The shebang is the first line of a Bash script that indicates the interpreter to be used when executing the script.
    • It starts with #! followed by the full path to the interpreter binary (e.g., /bin/bash).
  2. Why Use Shebang?

    • The shebang allows users to leverage different interpreters or customize script execution behavior.
    • Without a shebang, the default interpreter of the user’s shell will be used.
  3. Shebang Syntax:

    • The shebang directive takes the following form:
      #!/path/to/interpreter [arguments]
      
    • The directive must be the first line in the script.
    • White space after the shebang characters is optional.
  4. Examples:

    • Using the absolute path to the Bash binary:
      #!/bin/bash
      
    • Using the env utility (searches for the interpreter in the user’s $PATH):
      #!/usr/bin/env bash
      
  5. Adding Options:

    • To add options to the Bash shell, use the first approach:
      #!/bin/bash -x  # Enables debug mode
      
    • For the env method, use set to declare options:
      #!/usr/bin/env bash
      set -x  # Enables debug mode
      
  6. Creating a Simple Script:

    • Let’s create a script that prints “Hello, World”:
      nano hello_world
      
      #!/bin/bash
      echo "Hello, World"
      
    • Make the script executable:
      chmod +x hello_world
      
    • Run it:
      ./hello_world  # Outputs: Hello, World
      
  7. Overriding the Shebang:

    • To explicitly use a different interpreter, run the script with the desired shell:
      bash hello_world
      
    • Note that overriding the interpreter may lead to unexpected behavior.

Source: (https://linuxize.com/post/bash-shebang/) (https://linuxconfig.org/bash-script-shebang-usage-and-best-practices)

A terminal window with the text #! and the words bash shebang below it.

IMG Source: studytonight.com


Creating Files with a Counter Variable

Let’s explore how to create a for loop in Python that involves a counter variable. I’ll provide an example that demonstrates file creation using a counter within a for loop.

  1. Creating Files with a Counter Variable:
    Suppose you want to create a series of text files named file1.txt, file2.txt, file3.txt, and so on. You can achieve this by using a for loop with a counter variable. Here’s how you can do it:
# Example: Creating text files with a counter variable
for i in range(1, 6):  # Change the range as needed
    filename = f"file{i}.txt"
    with open(filename, "w") as file:
        file.write(f"This is content for {filename}\\n")
    print(f"Created {filename}")

In this example:

  • The range(1, 6) generates numbers from 1 to 5 (inclusive).
  • The f-string is used to dynamically create the filenames (file1.txt, file2.txt, etc.).
  • The with statement ensures that the file is properly closed after writing.
  • Adjust the range and file content as per your requirements.
  1. Explanation:
    • The for i in range(1, 6): line sets up the loop to iterate from 1 to 5 (inclusive).
    • Inside the loop, we create a filename using the value of i.
    • The with open(filename, "w") as file: line opens the file for writing.
    • We write some content to the file (in this case, just a sample message).
    • Finally, we print a message indicating that the file was created.

The image shows a Java program with a method that asks the user three addition questions and gives feedback based on their answers.

IMG Source: ytimg.com


Utilizing Conditional Statements and for Loops in Bash Scripting

Bash scripting with for loops can be quite powerful. Let’s explore how you can use conditional statements and for loops to filter files based on specific criteria.

  1. Simple for Loops with Numerical Lists:
    You can create a basic for loop that iterates over a list of numbers. For example, the following script prints the numbers from 1 to 5:

    for i in 1 2 3 4 5; do
        echo $i
    done
    

    In this loop, the variable i takes on each value in the list, and the loop body (the echo command) is executed for each value.

  2. Using Command Line Parameters:
    You can make your script more flexible by passing in filenames as command line parameters. For instance, the following script lists the details of files passed as arguments:

    #!/bin/bash
    for file in $*; do
        ls -lh "$file"
    done
    

    When you run this script with filenames as arguments (e.g., ./myscript.sh file1.txt file2.sh), it will display the file details using ls -lh.

  3. Filtering Files Based on Criteria:
    Suppose you want to filter files in a directory based on specific criteria (e.g., only .txt files). You can use a for loop along with conditional statements. Here’s an example:

    #!/bin/bash
    for filename in *.txt; do
        # Your custom logic here
        echo "Processing $filename"
    done
    

    Replace the echo line with your desired actions (e.g., copying, moving, or processing the files). The *.txt pattern matches all .txt files in the current directory.

Remember that the possibilities with for

A screenshot of a terminal window with a script to find files containing the string jane.

IMG Source: imgur.com


Error Handling Strategies in Bash Scripts

Improving error handling in Bash scripts, especially within loops, is essential for robust and reliable code. Here are some strategies you can employ:

  1. Exit on Error (errexit):

    • Use the set -o errexit command at the beginning of your script. This ensures that the script exits immediately if any command fails.
    • Example:
      #!/bin/bash
      set -o errexit
      # Your script logic here
      
    • This prevents the script from continuing execution after encountering an error.
  2. Ignore Errors with || true:

    • Sometimes you want to ignore errors and continue executing the script. You can use the || true construct after a command to achieve this.
    • Example:
      some_command || true
      
    • Even if some_command fails, the script will keep running.
  3. Custom Error Handling Function:

    • Define an error handling function that provides descriptive error messages and exits the script.
    • Example:
      #!/bin/bash
      PROGNAME=$(basename "$0")
      
      function error_exit {
          echo "${PROGNAME}: ${1:-"Unknown Error"}" 1>&2
          exit 1
      }
      
      # Example call of the error_exit function
      echo "Example of error with line number and message"
      error_exit "$LINENO: An error has occurred."
      
    • The error_exit function prints the error message along with the line number where the error occurred.
  4. Using Traps:

    • The trap command allows you to execute code when the script terminates.
    • For example, you can create a cleanup function to remove temporary files or handle other cleanup tasks.
    • Example:
      #!/bin/bash
      tempfiles=()
      
      cleanup() {
          rm -f "${tempfiles[@]}"
      }
      
      trap cleanup 0
      
      error() {
          local parent_lineno="$1"
          local message="$2"
          local code="${3:-1}"
          if [[ -n "$message" ]]; then
              echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"
          else
              echo "Error on or near line ${parent_lineno}; exiting with status ${code}"
          fi
          exit "${code}"
      }
      
      trap 'error ${LINENO}' ERR
      
      # Whenever you create a temporary file:
      temp_foo="$(mktemp -t foobar.XXXXXX)"
      tempfiles+=("$temp_foo")
      
    • The trap ensures that the cleanup function is called when the script exits.

References:

  1. Ensuring Bash Scripts Continue After Error
  2. Mastering Bash Script Loops
  3. Error Handling in Bash – Stack Overflow

A terminal window with a syntax error in a script.

IMG Source: imgur.com



In conclusion, mastering the art of creating files with Bash scripting for loops and if tests opens up a world of possibilities for automation and efficiency in your coding endeavors. By combining the iterative capabilities of for loops with the conditional logic of if tests, you can tailor your scripts to filter, process, and manage files with precision and accuracy. The examples and insights shared in this article are just the beginning of what you can achieve with Bash scripting.

So, roll up your sleeves, dive into the code, and start crafting your own dynamic scripts to streamline your file management tasks and elevate your programming prowess.

Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *