Home/Engineer/Linux / Shell/Practical Shell Scripting Ba…
Linux / ShellIntermediateubuntucentosmacosbashshellscript

Practical Shell Scripting Basics

Explains how to write bash scripts you can use immediately in production, covering variables, conditionals, loops, functions, and error handling.

Contents
  1. Basic Script Structure
  2. Variables
  3. Conditionals
  4. Loops
  5. Functions
  6. Error Handling

Basic Script Structure

Bash
#!/bin/bash
set -euo pipefail

main() {
 echo " when"
}

main "$@"

Variables

Bash
NAME="SecuThive"
echo ", $NAME"
echo ': $NAME' # Single quotes preserve the literal string

readonly VERSION="1.0.0"
PORT="${PORT:-8080}"       # Default value

SERVERS=("web1" "web2" "web3")
echo "${SERVERS[0]}"       # web1
echo "${#SERVERS[@]}"      # Number of elements

Conditionals

Bash
FILE="/etc/nginx/nginx.conf"

if [[ -f "$FILE" ]]; then
 echo "file "
elif [[ -d "$FILE" ]]; then
 echo ""
else
 echo ""
fi

if [[ "$ENV" == "production" ]]; then
 echo " "
fi

if [[ $COUNT -gt 10 ]]; then
 echo "10 "
fi

File Test Operators

ExpressionMeaning
-f FILERegular file exists
-d DIRDirectory exists
-e PATHPath exists
-r FILEFile is readable
-z STRINGString is empty
-n STRINGString is not empty

Loops

Bash
for server in "${SERVERS[@]}"; do
 echo ": $server"
  ssh "$server" "sudo systemctl restart myapp"
done

for i in {1..5}; do
 echo "when $i"
done

COUNT=0
while [[ $COUNT -lt 3 ]]; do
 echo " ..."
  sleep 1
  ((COUNT++))
done

Functions

Bash
log() {
  local level="$1"
  local msg="$2"
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $msg"
}

check_service() {
  local service="$1"
  if systemctl is-active --quiet "$service"; then
 log "INFO" "$service run "
    return 0
  else
 log "ERROR" "$service "
    return 1
  fi
}

check_service nginx || exit 1

Error Handling

Bash
if ! rsync -av /src/ user@host:/dest/; then
 log "ERROR" "rsync failed"
 exit 1
fi

TMPFILE=$(mktemp)
trap 'rm -f "$TMPFILE"; echo " "' EXIT
trap 'echo " : $LINENO"' ERR
#bash#shell#script
Editorial note

AI tools may assist drafting. Check the evidence in each guide for whether commands were run and which environment was used. Confirm the current docs for your version before applying instructions, and email us about errors. email us

Topic-related official docs (auto-linked · not per-claim sources)Linux man pages ↗

Questions & answers

Ask a question about this guide. We'll review and reply.