Creating a Persistent Sequence ID Counter With Bash

Published: 2022 May 27

Last edited: 2022 May 29

system administration Linux Bash shell script

Objective

In this post we’ll create a persistent counter for generating unique sequence IDs using a Bash script.

Building the solution

We’ll build the persistent counter using two files

Creating the counter file

Creating the counter file is very simple.

We’ll create a file named counter_next_test.txt with the Bash command:

touch counter_next_test.txt

And we’ll populate it with the value 1 with the command:

echo 1 > counter_next_test.txt 

Creating the incrementer script

We’ll create a file named seqid_incrementer.sh with the Bash command:

touch seqid_incrementer.sh

We’ll make it executable with the command:

chmod u+x seqid_incrementer.sh

We’ll populate the file with the following:

#!/bin/bash

# VARIABLES
filepath_of_persistent_counter=/home/user/test/counter_next_test.txt

# FUNCTION - incrementer
# Reads the first line from the persistent counter file, assigns it to the "next_seqid" variable, prints the next_seqid, increments the next_seqid by 1, and overwrites the persistent counter file with the new value.
incrementer() {

	# Read the first line of the specified file into the "next_seqid" variable.
	read next_seqid < "$filepath_of_persistent_counter"

	# Echo the contents of the "next_seqid" variable.
	echo "The next seqid is: $next_seqid"

	# Add 1 to the contents of the "next_seqid" variable and store the result in the "plus_one" variable.
	plus_one=$((next_seqid+1))

	# Overwrite the specified file with the contents of the "plus_one" variable.
	echo $plus_one > $filepath_of_persistent_counter

}

# MAIN program flow
incrementer

Most of this syntax has been used previously on the project. The new elements are below.

read next_seqid < "$filepath_of_persistent_counter" - The read command is a Bash Builtin command and this line reads a single line from the file referenced by the filepath_of_persistent_counter variable and stores it in the next_seqid variable.

plus_one=$((next_seqid+1)) - This command uses arithmetic expansion to add 1 to the value of next_seqid. This is one of several ways to increment a value.

Testing the solution

To test the script we’ll use the command:

./seqid_incrementer.sh 

And we’ll see the output below:

The next seqid is: 1

Rerun it and we’ll see:

The next seqid is: 2

Conclusion

We now have a persistent way to generate unique sequence IDs.

Copying Directory Structure With a Bash Script - With Help From ChatGPT AI

Published: 2024 January 22

Setting Up a Raspberry Pi as a Linux Print Server with CUPS

Published: 2024 January 19

Setting Up a Raspberry Pi Zero 2 W with Ubuntu Server

Published: 2024 January 04