Shell Script Basics
Structure of a Shell Script
A basic shell script typically consists of the following elements:
- Shebang: The first line of a shell script, also known as the "shebang" line, specifies the interpreter to be used for executing the script. For example,
#!/bin/bash
tells the system to use the Bash shell.
- Comments: Comments are used to provide explanations and documentation for the script. They are denoted by the
#
symbol.
- Commands: The main body of the script, which contains the commands to be executed.
Here's an example of a simple shell script:
#!/bin/bash
## This script prints a greeting
echo "Hello, LabEx!"
Variables
Shell scripts can use variables to store and manipulate data. Variables are defined using the following syntax:
variable_name=value
You can then use the variable by prefixing it with a $
symbol, like this:
name="LabEx"
echo "Welcome, $name!"
Shell scripts can accept user input using the read
command:
echo "What is your name?"
read name
echo "Hello, $name!"
They can also output data using commands like echo
, printf
, and cat
.
Control Structures
Shell scripts support various control structures, such as if-else
statements, for
loops, and while
loops, to control the flow of execution.
if [ "$name" == "LabEx" ]; then
echo "Welcome, LabEx!"
else
echo "Hello, stranger!"
fi
Functions
Shell scripts can define and call functions to encapsulate and reuse code.
greet() {
echo "Hello, $1!"
}
greet "LabEx"
Practical Examples
Here's an example of a shell script that automates the process of updating the system and installing a software package:
#!/bin/bash
## Update the system
sudo apt-get update
sudo apt-get upgrade -y
## Install a package
sudo apt-get install -y htop