01 - Shell Scripts Introduction
What is Shell Script?
A shell script is a text file containing a series of commands written for the Linux shell (e.g., bash, zsh, or sh).
Shell script in Linux is an easy to use time-saving solution for automating repetitive or complex set of tasks.
Key Features of Shell Scripts
Automation: Simplifies repetitive tasks.
Customizable: Can include logic like loops, conditionals, and functions.
Portable: Runs on any Linux system with the required shell.
Powerful: Can interact with other tools, programs, and system files.
Creating first shell script
vi <script-name>.sh
: This command will create a shell script and open it in a vi editor, after opening vi editor move all the relevant commands into the script file.$ vi create-and-launch-script.sh
Run / Execute a script
There are different ways to execute a shell script:
Execute a shell script with
bash
command:$ bash create-and-launch-script.sh
Execute a shell script as an
executable
or acommand
:$ create-and-launch-script.sh
Note: It is a best practice to not name your script with the
.sh
extension when you would like to create an executable of a script.$ create-and-launch-script
Configure a script to run as command
Whenever a command is run at a Linux system, the OS looks at the path configured in the
$PATH
environment variable to locate the executable or script for the command.If it cannot find the command in the
$PATH
then acommand not found
error will be thrown.To add our script as a command, append the path to the directory containing the script to the end of the
$PATH
variable.$ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/michael
A better way to do this is to append the path to the directory to $PATH variable:
$ export PATH=$PATH:/home/michael
Now, run the script as a command:
$ create-and-launch-script
which <command>
: To see the location of the command:$ which create-and-launch-script
Executing a script
For a shell script to work, we must set the correct permissions to the file, if the permissions are not set a "Permission Denied" error will be thrown when you run the script for the first time.
ls -l <script>
: To inspect the file permissions:$ ls -l /home/michael/create-and-launch-script
chmod
: Add executable permissions to a file.$ chmod +x /home/michael/create-and-launch-script $ ls -l /home/michael/create-and-launch-script
Now, run the script:
$ /home/michael/create-and-launch-script
Variables
In shell scripting, variables allow the user to store and use the data dynamically in the script.
They make scripts more flexible and reusable by allowing dynamic data to be used instead of hardcoding values.
Key Points
A variable is a value that can vary or change.
A variable always has a
$
sign before it's name (not while defining).A variable name only contain alphanumeric or underscores
A variable is case sensitive as well.
Defining Variables
No spaces are allowed around the
=
when assigning values and do not use$
sign before the variable name.$ mission_name=lunar-mission
Accessing Variables
Use a
$
prefix to reference a variable's value.$ echo $mission_name
We can also use variables to store the result of another command and print it.
$ rocket_status=$(rocket-status $mission_name) $ echo "Status of launch: $rocket_status"
Types of Variables
Local Variables:
Defined and used within the script or a function.
$ my_var="Hello" $ echo $my_var
Environment Variables:
System-wide variables available to all processes.
$ export PATH $ echo $HOME
Positional Variables:
Special variables representing script arguments.
$ echo "Script Name: $0" $ echo "First Argument: $1"
Special Variables:
Variables with predefined meanings.
$?
: Exit status of the last command.$$
: Process ID (PID) of the current shell.$#
: Number of arguments passed to the script.$@
: All arguments as separate words.$*
: All arguments as a single string.
Command Line Arguments and Read Inputs
Command Line Arguments
Command line arguments are inputs provided to a shell script at runtime. They allow the script to accept data dynamically, making it more versatile and reusable.
The arguments passed are accessed using special positional variables inside the script.
Accessing Command Line Arguments
$0
: The name of the script.$1
,$2
, ...: The first, second, and subsequent arguments.$#
: The total number of arguments passed.$@
: All arguments as separate words.$*
: All arguments as a single string.$?
: The exit status of the last command.$$
: The current script's process ID (PID).
Read Inputs
The
read
command in shell scripting is used to take input from the user during script execution.It pauses the script until the user provides input and then assigns the entered value to a variable.
Syntax of read
$ read -p "Enter mission name:" mission_name
mission_name
: The variable where the input will be stored.Options:
-p
: Display a prompt message.-s
: Silent input (useful for passwords).-t
: Timeout for input.-n
: Read a specific number of characters.
Arithmetic Operators
- Arithmetic operations in shell scripting allow you to perform mathematical calculations. Bash supports basic arithmetic operations like addition, subtraction, multiplication, division, and modulus.
Methods for Arithmetic Operations
Using expr
Command
The
expr
command evaluates expressions and returns the result.$ expr 6 + 3 # addition (there must be space between the values and the operator) $ expr $A + $B # where, A=6 and B=3 $ expr 6 \* 3 # multiplication (escape the * symbol using \ like \*, because * is reserved character in shell
Using Double Parentheses $(( ))
Double parentheses helps in performing arithmetic evaluation same as most of the programming languages like C.
Double parentheses are the most common way to perform arithmetic in Bash.
$ echo $(( 6 + 3 )) # use echo to print the output on the screen $ echo $(( A+B )) # where, A=6 and B=3, there is no need of space and $ inside a parenthesis $ echo $((A+B)) # where, A=6 and B=3, there is no need of space and $ inside a parenthesis $ echo $((A*B)) # where, A=6 and B=3, no need of escape character (\)
Can also use programming language C type manipulations of variables.
$ echo $(( ++A )) # increment $ echo $(( --A )) # decrement $ echo $(( A++ )) $ echo $(( A-- ))
Using let
Command
The
let
command is used to perform arithmetic operations directly.#!/bin/bash A=10 B=5 let sum=A+B echo "Sum: $sum"
Using bc
Command (For Floating-Point Arithmetic)
Bash does not support floating-point arithmetic natively, but the
bc
command can be used for such calculations.#!/bin/bash A=10.5 B=2.5 echo $A * $B | bc -l
Key Differences:
| Command | Use Case | Floating-Point Support | Integer Support | | --- | --- | --- | --- | | `echo "$A * $B" | bc -l` | Preferred for floating-point | ✅ Yes | | `echo $((A * B)) | bc -l` | Works only for integers | ❌ No |
Correct Usage
Use
echo "$A * $B" | bc -l
for calculations involving floating-point numbers.Use
$((A * B))
directly for integer calculations, without needingbc
.
Note:
- Both the
expr
anddouble parentheses
only return decimal output, they do not support floating-point numbers.