Learn › Linux

Bash Scripting Basics for Windows Admins

Write your first useful Bash scripts: variables, if, loops, arguments, exit codes and safe defaults – with a PowerShell comparison for every concept.

Intermediate 11 min read
By Gopinath Karthikeyan

If you can write PowerShell scripts, Bash will feel familiar – with one big difference: Bash works with text, not objects. This guide covers enough Bash to automate everyday Linux tasks and to read the scripts you’ll find in Jenkins jobs and Docker images.

Your first script

#!/usr/bin/env bash
# disk-check.sh – warn when a filesystem is over a threshold
set -euo pipefail

THRESHOLD=${1:-80}          # first argument, default 80

df -P --output=pcent,target | tail -n +2 | while read -r pct mount; do
    used=${pct%\%}          # strip the % sign
    if (( used >= THRESHOLD )); then
        echo "WARNING: $mount is ${used}% full"
    fi
done
chmod +x disk-check.sh
./disk-check.sh 70
  • #!/usr/bin/env bash (the shebang) says which interpreter runs the file.
  • chmod +x makes it executable.

Safe defaults: set -euo pipefail

Put this near the top of every script:

  • -e – stop when a command fails (like $ErrorActionPreference = 'Stop')
  • -u – error on undefined variables (catches typos)
  • -o pipefail – a pipeline fails if any part fails, not only the last

Variables

name="SRV01"                 # no spaces around =
echo "Checking $name"
echo "Checking ${name}-backup"
today=$(date +%F)            # command output into a variable

Always quote variables: "$file", not $file. Unquoted variables with spaces in them cause some of the nastiest Bash bugs.

Arguments

Bash Meaning
$1, $2 First, second argument
$# Number of arguments
$@ All arguments
${1:-default} First argument, or a default

if

if [[ -f /etc/nginx/nginx.conf ]]; then
    echo "nginx config exists"
elif [[ -d /etc/apache2 ]]; then
    echo "apache is installed"
else
    echo "no web server config found"
fi

Useful tests: -f file exists, -d directory exists, -z "$v" empty string, "$a" == "$b" strings equal, (( n > 5 )) numbers.

Loops

for host in srv01 srv02 srv03; do
    if ping -c 1 -W 2 "$host" > /dev/null 2>&1; then
        echo "$host UP"
    else
        echo "$host DOWN"
    fi
done

while read -r line; do
    echo "Processing $line"
done < servers.txt

Functions and exit codes

log() { echo "$(date '+%F %T') $*"; }

check_service() {
    local svc=$1
    if systemctl is-active --quiet "$svc"; then
        log "$svc is running"
    else
        log "$svc is NOT running"
        return 1
    fi
}

check_service nginx || exit 1

Exit code 0 = success, anything else = failure. $? holds the last command’s exit code. Jenkins, cron and Ansible all rely on it.

Text tools you’ll pipe together

grep -i error app.log | wc -l                 # count errors
cut -d: -f1 /etc/passwd                       # first field of each line
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head   # top client IPs
sed 's/old/new/g' file.txt                    # replace text

Bash vs PowerShell at a glance

Concept PowerShell Bash
Variable $name = 'x' name="x"
Stop on error $ErrorActionPreference='Stop' set -e
If file exists Test-Path [[ -f file ]]
Loop foreach ($s in $list) for s in $list; do ... done
Output of a command $(Get-Date) $(date)

Check your scripts

shellcheck (sudo apt install shellcheck) finds quoting mistakes and common bugs – the Bash equivalent of PSScriptAnalyzer. Run it before you commit.

What’s next

Next: SSH keys and server hardening.

LinuxBashScriptingAutomationIntermediate

Gopinath Karthikeyan

Gopinath Karthikeyan – Windows Site Reliability Engineer with about 12 years in enterprise Windows Server infrastructure, and founder of WinOps Academy. YouTube · LinkedIn

More in Linux