Lets look at an example,
$ counter=0
$ echo counter
0
Once the variable counter is created, it's there until you close the terminal window. The value may change but the variable will be there untill declared shell variable.
You can increment it with the operator (++)
$ let counter++
$ echo counter
1
Lets build a simple script, called counter_test.sh, that will keep on counting until we tell it to stop by pressing Ctrl+C (note- Ctrl+C aborts any process on the command line (sending interrupt signal)).
The first line of any chell script is what's commonly called a shebang: a pound sign, followed by an exclamation point, followed by the path to the shell.
- /bin/sh is a standard shortcut to the shell program on Linux systems. Usually, this file is just a link to the actual shell program )e.g. /bin/bash) but using the standard name ensures that you r script till stull work on a system that uses a different shell.
And then write the program
#!/bin/sh
Every shell script must begin with this. The next line of our script will set a value fo the counter vartiable:
counter=0
In other words we are starting at zero. Next we'll add a loop to the program. We'll make it an infinite loop, so the user will have to send an interrupt signal to quit the program.
while true;
do
# content of loop
done
Now all we have to do is the content. Printing the varianle counter and incrementing it with the let command
while true;
do
echo $counter
let counter++
sleep 1;
done
Save the file
The last thing we must do is change its permissions.
$ chmod u+x counter.sh
Execute it
./counter.sh
This will tell the shell to execute a file named counter.sh within the current working directory.
No comments:
Post a Comment