Ravindra BagaleCourses & study guides

Chapter 4: Linux Advanced Commands

4.13 Basic shell scripting

Ekdum simple aahe — a script is just the commands you already know, saved in a file. Let's write one together.

A shell script is a text file containing commands, run top to bottom. It is the first step towards automation (and towards EC2 user data, which runs a script at first boot).

#!/bin/bash
# file: sysinfo.sh  - print a quick health report
set -uo pipefail         # stop on undefined variables and pipe failures

NAME=$(hostname)
echo "Health report for $NAME at $(date)"
echo "---------------------------------"
echo "Uptime : $(uptime -p)"
echo "Disk / : $(df -h / | awk 'NR==2 {print $5 " used"}')"
echo "Memory : $(free -m | awk '/Mem/ {printf "%d/%d MB used", $3, $2}')"

# if-else
if systemctl is-active --quiet nginx; then
  echo "Nginx  : running"
else
  echo "Nginx  : NOT running"
fi

# loop
for svc in sshd crond; do
  echo "$svc -> $(systemctl is-active $svc 2>/dev/null)"
done

# function with argument
check_port() {
  if ss -tln | grep -q ":$1 "; then echo "Port $1 open"; else echo "Port $1 closed"; fi
}
check_port 22
check_port 80
nano sysinfo.sh        # paste the script, save with Ctrl+O, exit with Ctrl+X
chmod +x sysinfo.sh
./sysinfo.sh
Concept Syntax
Variable NAME="Asha", use $NAME or ${NAME} (no spaces around =)
Command output TODAY=$(date +%F)
Arguments $1, $2, all: $@, count: $#
Exit status of last command $? (0 = success)
Test file exists if [ -​f /​etc/​nginx/​nginx.​conf ]; then ... fi
Test directory [ -d /var/www ]
Compare numbers [ "$a" -gt 10 ] (-​eq -​ne -​lt -​le -​ge)
Compare strings [ "$a" = "yes" ]
Read input read -​p "Enter name: " NAME