Bash Script Basics
#!/bin/bash, variables, echo, read, exit codes, making scripts executable
Skills taught: linux.shebang, linux.bash-variables, linux.exit-codes, linux.script-structure
Your first bash script
#!/bin/bash
# The shebang line tells the OS which interpreter to use
# #!/bin/bash — bash
# #!/bin/sh — POSIX sh (more portable, fewer features)
# #!/usr/bin/env bash — find bash in PATH (recommended)
# Comment: lines starting with # are comments
echo "Hello, World!"
# Variables (no spaces around =)
NAME="Alice"
AGE=30
GREETING="Hello, $NAME! You are $AGE years old."
echo $GREETING
# Command substitution: capture command output
CURRENT_DATE=$(date +%Y-%m-%d)
FILE_COUNT=$(ls | wc -l)
echo "Today is $CURRENT_DATE, files: $FILE_COUNT"
# Read user input
echo -n "Enter your name: " # -n: no newline
read USER_NAME
echo "Hello, $USER_NAME!"
Making scripts executable and running them
# Make it executable
chmod +x hello.sh
# Run it
./hello.sh # ./ required (not just hello.sh)
bash hello.sh # run with bash explicitly (no chmod needed)
sh hello.sh # run with sh
# Pass arguments to a script
./greet.sh Alice 30
# Inside the script, access arguments:
# $1 = first argument ('Alice')
# $2 = second argument ('30')
# $@ = all arguments
# $# = number of arguments
# $0 = script name
Exit codes and $?
#!/usr/bin/env bash
# Every command returns an exit code: 0 = success, 1-255 = error
ls /existing/path # exit code 0
echo "Exit: $?" # → 0
ls /nonexistent # exit code 2
echo "Exit: $?" # → 2 (non-zero = failure)
# exit: set script's exit code
if [ ! -f config.txt ]; then
echo "Error: config.txt not found" >&2 # write error to stderr
exit 1 # non-zero = failure
fi
echo "Config found"
exit 0 # success (optional — scripts exit 0 if they reach the end)
# Use exit codes in pipelines
if grep -q "ERROR" server.log; then
echo "Errors found in log!"
fi
# grep returns 0 if match found, 1 if not, 2 if error
Tip: Start scripts with set -euo pipefail. -e exits on error, -u treats unset variables as errors, -o pipefail makes pipelines fail if any command fails. This catches bugs that would otherwise silently continue.
Frequently Asked Questions
Why do I need ./ before the script name?
For security, the shell does not look in the current directory (.) when searching for commands — only in $PATH directories. ./hello.sh explicitly says 'run hello.sh in the current directory.' Without ./, the shell would search $PATH and not find hello.sh. You can add . to $PATH but it is a security risk (a malicious ls script in any directory you visit would run).