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.
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:
oldFiles.txt
.../data/list.txt
.oldFiles.txt
.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:
What is the Shebang?
#!
followed by the full path to the interpreter binary (e.g., /bin/bash
).Why Use Shebang?
Shebang Syntax:
#!/path/to/interpreter [arguments]
Examples:
#!/bin/bash
env
utility (searches for the interpreter in the user’s $PATH
):
#!/usr/bin/env bash
Adding Options:
#!/bin/bash -x # Enables debug mode
env
method, use set
to declare options:
#!/usr/bin/env bash
set -x # Enables debug mode
Creating a Simple Script:
nano hello_world
#!/bin/bash
echo "Hello, World"
chmod +x hello_world
./hello_world # Outputs: Hello, World
Overriding the Shebang:
bash hello_world
Source: (https://linuxize.com/post/bash-shebang/) (https://linuxconfig.org/bash-script-shebang-usage-and-best-practices)
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.
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:
range(1, 6)
generates numbers from 1 to 5 (inclusive).f-string
is used to dynamically create the filenames (file1.txt
, file2.txt
, etc.).with
statement ensures that the file is properly closed after writing.for i in range(1, 6):
line sets up the loop to iterate from 1 to 5 (inclusive).i
.with open(filename, "w") as file:
line opens the file for writing.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.
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.
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
.
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
Improving error handling in Bash scripts, especially within loops, is essential for robust and reliable code. Here are some strategies you can employ:
Exit on Error (errexit):
set -o errexit
command at the beginning of your script. This ensures that the script exits immediately if any command fails.#!/bin/bash
set -o errexit
# Your script logic here
Ignore Errors with || true
:
|| true
construct after a command to achieve this.some_command || true
some_command
fails, the script will keep running.Custom Error Handling Function:
#!/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."
error_exit
function prints the error message along with the line number where the error occurred.Using Traps:
trap
command allows you to execute code when the script terminates.#!/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")
trap
ensures that the cleanup function is called when the script exits.References:
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.