Bash Scripting Basics: Build Your First Reliable Script

Bash scripting is where repeatable automation starts. Instead of typing the same command sequence by hand, you can package it into a script that is consistent, testable, and easy to share.

What Bash scripting solves

Bash scripts are a practical fit when you need quick automation around files, processes, environment setup, or command orchestration.

Use a script when:

  • You run the same command sequence often
  • You need repeatable behavior across machines
  • You want to wrap several tools behind one interface

Create and run your first script

Start with the shebang so the OS knows which interpreter to use.

#!/usr/bin/env bash
echo "Hello from Bash"

Save this as hello.sh, then make it executable:

chmod +x hello.sh
./hello.sh

You can also run it without execute permissions by passing it to Bash directly:

bash hello.sh

Variables and quoting basics

Variables in Bash are untyped strings by default, and quoting controls how expansion and whitespace are handled.

#!/usr/bin/env bash

name="John"
site="thelinux.pro"
path_with_space="/tmp/my folder"

echo "Name is $name"
echo 'Single quotes do not expand $name'
echo "Site: ${site}"
echo "Path: ${path_with_space}"

Practical quoting habits:

  • Use double quotes around variable expansions by default
  • Use braces like ${var} when concatenating text
  • Use single quotes for literal strings that should not expand

Command substitution and formatted output

Use $() to capture command output and printf when you need predictable formatting.

#!/usr/bin/env bash

today="$(date +%F)"
kernel="$(uname -r)"

printf "Date: %s\n" "$today"
printf "Kernel: %s\n" "$kernel"

Exit codes and script flow

Every command returns an exit code where 0 means success and non-zero means failure.

#!/usr/bin/env bash

ls /tmp >/dev/null
echo "ls exit code: $?"

ls /does-not-exist >/dev/null 2>&1
echo "missing path exit code: $?"

You will build on this in later posts with stricter failure handling.

A practical first script

This script prints a greeting and checks whether a required file exists before continuing.

#!/usr/bin/env bash

target_file="${1:-/etc/hosts}"

echo "Starting script"
echo "Checking file: ${target_file}"

if [[ -f "$target_file" ]]; then
  echo "File exists and is ready"
  exit 0
fi

echo "File not found: ${target_file}"
exit 1

Run it:

chmod +x check-file.sh
./check-file.sh /etc/hosts
./check-file.sh /tmp/missing-file

Next in this series

Next, we will focus on output redirection, stderr handling, and pipelines so you can capture, route, and inspect script output cleanly.