Understanding Shell Scripting
Shell scripting is a powerful way to automate repetitive tasks, manage system processes, and handle system administration tasks in a Linux environment. By writing simple scripts, you can significantly improve productivity and reduce errors. This blog will introduce you to shell scripting basics, followed by examples of real-world tasks using scripts to install packages and create backups.
Example 1: Installing Nginx
Here’s a script that installs the popular web server Nginx:
#!/bin/bash
<<note
This script will install nginx
note
echo "*************INSTALLING NGINX*************"
sudo apt-get update
sudo apt-get install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
echo "*************INSTALLED NGINX*************"
Explanation
- sudo systemctl start nginx starts the web server immediately.
- sudo systemctl enable nginx ensures Nginx starts automatically on system boot.
Example 2: Installing Any Package
Sometimes, you might want a generic script to install any package by simply passing its name as an argument.
Recommended by LinkedIn
#!/bin/bash
<<note
This Script will install any package passed as argument
note
echo "**********INSTALLING $1**********"
sudo apt-get update
sudo apt-get install $1 -y
sudo systemctl start $1
sudo systemctl enable $1
echo "**********INSTALLED $1**********"
Explanation
./install.sh apache2 # Installs Apache2
./install.sh mysql # Installs MySQL
4. Starting and Enabling the Package:After installation, the script attempts to start and enable the service.
Example 3: Creating Backups
Backups are essential for safeguarding data. The following script creates a compressed backup of any directory.
#!/bin/bash
<<note
This script takes backup of any destination path given in argument
./backup.sh /home/ubuntu/scripts
note
function create_backup() {
timestamp=$(date '+%Y-%m-%d_%H-%M-%S')
backup_dir="/home/ubuntu/backups/${timestamp}_backup.zip"
zip -r $backup_dir $1
echo "BACKUP COMPLETE"
}
create_backup $1
Explanation
./backup.sh /home/ubuntu/scripts