Bash Scripting - Script execution counter

This Linux shell script does nothing than just increasing n value every time it is executed and then keep the value in a file. When the value goes greater than 10, it will drop back to 1. Uhhh... this reminds me to the increasing of the fuel price. But that fuel price will just increase and will never drop back... Lol... Anyway, I wrote this bash script just to make a permanent variable to be used as bash script running counter. With this code, I can count how many time the script have been executed.

Here's the code:

#!/bin/sh

nfilename="./nvalue"

n=0
touch $nfilename
. $nfilename

echo "current n value is $n"

n=$(expr $n + 1)

if [ $n -gt 10 ]; then
   n=1
fi

echo "new n value is $n"

echo "n=$n" > $nfilename

Here's the step for testing the script for newbies bash scripter.

1. Create one text file in your home folder. In this example I'm using ncounter as the file name:

apogee@apogee-persiasys:~ gedit ncounter

2. Copy and paste the codes in this file, then save and close it.

3. Change the file permission to executable:

apogee@apogee-persiasys:~ chmod +x ncounter

4. Then you can test it... here's my output example:

apogee@apogee-persiasys:~$ ./ncounter 
current n value is 0
new n value is 1
apogee@apogee-persiasys:~$ ./ncounter 
current n value is 1
new n value is 2
apogee@apogee-persiasys:~$ ./ncounter 
current n value is 2
new n value is 3
apogee@apogee-persiasys:~$ ./ncounter 
current n value is 3
new n value is 4
apogee@apogee-persiasys:~$ 

Feel free to experiment and change the ./nvalue file location to somewhere else where you have read and write permission. This is just another linux shell script that I haven't used yet... heheh


Comments

Damitr Mazanov said…
Thanks for the script, it has helped me a lot. Will send detailed report of how it was used.

regard

Damitr

Popular posts from this blog

How to Create Hyperlink on Blogger Post

How to Add a Sudo User on AlmaLinux 9.2 (Turquoise Kodkod): A Step-by-Step Guide

How to Show and Hide Text in Blog Post