Linux / Bash
Beginner
1 min read
Bash Script Basics: Variables and Arguments
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}'"
Related Resources
Linux / Bash Reference
Complete tag & property list
Linux / Bash How-To Guides
Step-by-step practical guides
Linux / Bash Exercises
Practice what you've learned
More in Linux / Bash