Home

Bash Shell Scripting

Overview

In this project, I had to write a Bash script that would create 25 empty files with sequential numbering. The script needed to be designed to create the next batch of 25 files each time it ran, starting with the last or maximum number that already existed in the directory.

Project Requirements

My Implementation Steps

Step 1: Setting Up the Base Filename

I started by defining the base filename using my name "Alex" that would be used for all files.

# Set the base file name using my name
baseName="Alex"

Step 2: Finding the Highest Existing Number

Next, I needed to determine what the highest existing number was in the current directory so I could start numbering from there. This required using multiple commands chained together.

# Find the highest existing number in the current directory
maxNumber=$(ls ${baseName}[0-9]* 2>/dev/null | grep -o '[0-9]*' | sort -n | tail -n 1)
startNumber=$((maxNumber + 1))

The command chain first lists all files starting with "Alex" followed by numbers, then extracts just the numbers, sorts them numerically, and takes the highest value.

Step 3: Creating the Sequence of Files

I implemented a for loop to create 25 sequential files using the touch command.

# Create 25 new empty files with sequential numbering
for ((i=0; i<25; i++)); do
touch "${baseName}$((startNumber + i))"
done

Step 4: Validating the Results

To verify the script worked properly, I added a command to display all files in the directory:

# Display the list of files in the current directory
ls -l

Complete Script

Here's my complete Bash script that fulfills all the requirements:

#!/bin/bash

# Set the base file name using my name
baseName="Alex"

# Find the highest existing number in the current directory
maxNumber=$(ls ${baseName}[0-9]* 2>/dev/null | grep -o '[0-9]*' | sort -n | tail -n 1)
startNumber=$((maxNumber + 1))

# Create 25 new empty files with sequential numbering
for ((i=0; i<25; i++)); do
touch "${baseName}$((startNumber + i))"
done

# Display the list of files in the current directory
ls -l

Key Learning Points

The 2>/dev/null part of the command redirects any error messages to /dev/null, which prevents errors from appearing if no matching files exist yet.

Related Topics