SyntaxStudy
Sign Up
Linux / Bash Bash Script Basics: Variables and Arguments
Linux / Bash Beginner 1 min read

Bash Script Basics: Variables and Arguments

A Bash script is a text file containing a sequence of shell commands. The first line, the shebang (`#!/bin/bash`), tells the kernel which interpreter to use. After making the file executable with `chmod +x`, you can run it directly. Scripts automate repetitive tasks, enforce consistent procedures, and serve as executable documentation. Variables in Bash are assigned with `VAR=value` (no spaces around `=`) and expanded with `$VAR` or the safer `${VAR}` form. Bash does not enforce types — all values are strings unless arithmetic context is used. Variables are local to the current shell by default; `export` makes them available to child processes as environment variables. Positional parameters `$1`, `$2`, ... `$9` hold the arguments passed to the script on the command line. `$0` is the script name, `$#` is the argument count, `$@` expands to all arguments as separate words, and `$*` expands to all arguments as a single word. `$?` holds the exit status of the last command (0 = success), and `$$` holds the PID of the current shell.
Example
#!/bin/bash
# Script: greet.sh
# Usage: ./greet.sh <name> <city>

# --- Script metadata ---
SCRIPT_NAME=$0
ARG_COUNT=$#

echo "Script: $SCRIPT_NAME"
echo "Arguments received: $ARG_COUNT"

# --- Positional parameters ---
NAME=$1
CITY=${2:-"Unknown City"}     # Default value if $2 is empty

echo "Hello, $NAME! You are from $CITY."

# --- All arguments ---
echo "All args: $@"
for arg in "$@"; do
    echo "  Arg: $arg"
done

# --- Variable assignment and expansion ---
GREETING="Welcome"
FULL_MSG="${GREETING}, ${NAME}!"
echo "$FULL_MSG"

# --- Exit status ---
ls /nonexistent 2>/dev/null
echo "Exit status of last command: $?"

ls /tmp 2>/dev/null
echo "Exit status: $?"    # 0 = success

# --- Current shell PID ---
echo "This script's PID: $$"

# --- Read-only variable ---
readonly MAX_RETRIES=3
echo "Max retries: $MAX_RETRIES"

# --- Unset a variable ---
TEMP_VAR="temporary"
unset TEMP_VAR
echo "TEMP_VAR is now: '${TEMP_VAR}'"