Quick Tutorial on How to Use Shell Scripting in Linux: Coin Toss App

Simply put, a Shell Script is a program that is run by a UNIX/Linux shell. It is a file that contains a series of commands which are executed sequentially as if they were entered on the command line interface (CLI) or terminal.

In this quick tutorial on Shell Scripting, we will write a simple program to toss a coin. Basically, the output of our program should be either HEADS or TAILS (of course, randomly).

To start with, the first line of a shell script should indicate which interpreter/shell is to be used to execute the script. In this tutorial we will be using /bin/bash and it will be denoted as #!/bin/bash which is called a shebang!

Next, we will be using an internal Bash function - a shell variable named RANDOM. It returns a random (actually, pseudorandom) integer in the range 0-32767. We will use this variable to get 2 random values – either 0 (for HEADS) or 1 (for TAILS). This will be done via a simple arithmetic operation in shell using % (Modulus operator, returns remainder), $((RANDOM%2)) and this will be stored in a result variable. So, the second line of our program becomes Result=$((RANDOM%2)) – Note that there should be no space around = (assignment operator) while assigning value to a variable in shell scripts.

At last, we just need to print HEADS if we got 0 or TAILS if we got 1, in the Result variable. Perhaps you guessed it by now, we will use if conditional statements for this. Within the conditions, we will compare the value of Result variable with 0 and 1; and print HEADS or TAILS accordingly. For this, the operator for integer comparison -eq (is equal to) is used to check if the value of two operands are equal or not.

Ergo, our shell script looks like the following:

 

#!/bin/bash
Result=$((RANDOM%2))
if [[ ${Result} -eq 0 ]]; then
    echo HEADS
elif [[ ${Result} -eq 1 ]]; then
    echo TAILS
fi

 

Let’s say we name the script cointoss.sh – Note that .sh is only to make it identifiable for user(s) that the file/script is a shell script. And, Linux is an Extensionless system.

Finally, to run the script we need to make it executable and that can be done by using the chmod command – chmod +x cointoss.sh

Few script executions:

 

$ ./cointoss.sh

TAILS

$ ./cointoss.sh

HEADS

$ ./cointoss.sh

HEADS

$ ./cointoss.sh

TAILS

 

 

To wrap up, in this quick tutorial about writing shell scripts, we learned about shebang, RANDOM, variable assignment, an arithmetic operation using Modulus operator %, if conditional statements, integer comparison operator -eq and executing a shell script.

Nawaz is a Linux CLI enthusiast and likes sharing tips and tutorials related to command-line and shell scripting. He can be reached via LinkedIn.

Load Disqus comments