|$ curl https://forge-ai.dev/api/markdown?path=docs/linux/shell-scripting
$cat docs/shell-scripting.md
updated Recently·28 min read·published

Shell Scripting

LinuxBashScriptingAutomationIntermediate🎯Free Tools
Introduction

Shell scripts glue together command-line tools to automate backups, deployments, testing, and system administration. Bash is the default shell on most Linux systems and the lingua franca of automation.

Hello World
hello.sh
Bash
1#!/usr/bin/env bash
2set -euo pipefail
3
4echo "Hello, ForgeLearn!"
5
6# Make executable and run
7# chmod +x script.sh
8# ./script.sh

best practice

set -euo pipefail is the safety harness: exit on error (-e), treat unset variables as errors (-u), and fail pipelines on any error (-o pipefail).
Variables
variables.sh
Bash
1name="Alice"
2echo "Hello, $name"
3echo "Hello, ${name}!"
4
5# Command substitution
6now=$(date +%Y-%m-%d)
7echo "Today is $now"
8
9# Default values
10port="${PORT:-3000}"
11name="${NAME:?NAME is required}"
12
13# Arithmetic
14sum=$((3 + 4))
15echo "$sum"
Conditionals
conditionals.sh
Bash
1file="data.txt"
2
3if [[ -f "$file" ]]; then
4 echo "File exists"
5elif [[ -d "$file" ]]; then
6 echo "Directory exists"
7else
8 echo "Not found"
9fi
10
11# String comparison
12if [[ "$USER" == "root" ]]; then
13 echo "Running as root"
14fi
15
16# Numeric comparison
17if (( count > 0 )); then
18 echo "Count is positive"
19fi
Loops
loops.sh
Bash
1# For loop over list
2for name in alice bob carol; do
3 echo "Hello, $name"
4done
5
6# For loop over files
7for file in *.log; do
8 echo "Processing $file"
9done
10
11# While loop
12i=0
13while (( i < 5 )); do
14 echo "$i"
15 ((i++))
16done
17
18# Read lines from command output
19while read -r line; do
20 echo "$line"
21done < input.txt
Functions
functions.sh
Bash
1#!/usr/bin/env bash
2set -euo pipefail
3
4greet() {
5 local name="$1"
6 echo "Hello, $name"
7}
8
9log() {
10 local level="$1"
11 local message="$2"
12 echo "[${level}] $(date -Iseconds) $message" >&2
13}
14
15result=$(greet "Alice")
16echo "$result"
17log "INFO" "Script started"
Arguments
arguments.sh
Bash
1#!/usr/bin/env bash
2set -euo pipefail
3
4input="$1"
5output="${2:-output.txt}"
6
7if [[ $# -lt 1 ]]; then
8 echo "Usage: $0 <input> [output]" >&2
9 exit 1
10fi
11
12echo "Input: $input"
13echo "Output: $output"
Best Practices
  • Always quote variables: "$var" instead of $var.
  • Use set -euo pipefail unless you have a reason not to.
  • Prefer [[ ]] over [ ] for conditionals.
  • Use local inside functions to avoid leaking variables.
  • Validate inputs and print usage messages.
  • For complex logic, consider Python instead of Bash.