iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Parameters & Defaults

Bash positional + special parameters: \$1 / \$@ / \$* / \$# / \$? / \$\$, defaults, and the patterns for safe scripts.

Linux — Bash parameters

EXAMPLE
# ===== Positional parameters =====
# $0          script / function name
# $1, $2, ... arguments
# $10+        requires ${10}, ${11}, etc.

myscript.sh foo bar baz
# Inside: $0=myscript.sh, $1=foo, $2=bar, $3=baz

# ===== All arguments =====
# $@         all args as SEPARATE words (preferred)
# $*         all args as ONE string (joined by IFS)
# $#         count

for arg in "$@"; do echo "$arg"; done

# ===== Special parameters =====
# $?         exit status of last command
# $$         current PID
# $!         PID of last background command
# $-         current shell flags

cmd
echo "exit code: $?"

# ===== Default values =====
# ${var:-default}    if var unset or empty, use default
# ${var:=default}    set var to default if empty
# ${var:?error}      exit with error if empty
# ${var:+value}      use value if var is set

name="${1:-Anonymous}"            # default if not provided
config="${CONFIG:-/etc/app.conf}"
: "${REQUIRED?Must set REQUIRED}"  # error out if missing

# ===== String operations =====
str='hello.txt'
${str%.*}        # 'hello' (strip shortest match from end)
${str%%.*}       # 'hello'
${str#*.}        # 'txt'  (strip shortest from start)
${str/hello/HI}  # 'HI.txt' (replace first)
${str//l/L}      # 'heLLo.txt' (replace all)
${str:1:3}       # 'ell' (substring)
${#str}          # 11 (length)
${str^^}         # 'HELLO.TXT' (uppercase)
${str,,}         # 'hello.txt' (lowercase)

# ===== Parsing options with getopts =====
while getopts ':v:h' opt; do
  case $opt in
    v) version=$OPTARG ;;
    h) echo 'Usage: ...'; exit 0 ;;
    \?) echo "Unknown: -$OPTARG" >&2; exit 1 ;;
    :) echo "Missing arg for -$OPTARG" >&2; exit 1 ;;
  esac
done
shift $((OPTIND - 1))   # remove processed options

# ===== Strict mode =====
set -euo pipefail
# -e: exit on error
# -u: error on undefined variables
# -o pipefail: pipe fails if any command in pipe fails

IFS=$'\n\t'       # safer Internal Field Separator

# ===== Quoting =====
echo "$var"        # double quote: variable expansion + safe word splitting
echo '$var'        # single quote: NO expansion (literal)
echo "\"hello\""  # escape double quote inside double quote

# ALWAYS quote variables; rare exception: when you DELIBERATELY want word splitting.

# ===== Patterns =====
# - set -euo pipefail at top of every script
# - 'local' for all variables inside functions
# - ${var:-default} for safe defaults
# - shellcheck on every script
# - Quote everything

# ===== Pitfalls =====
# - Unquoted $var with spaces -> word splitting bugs
# - $@ vs $*; use "$@" almost always
# - Missing 'shift' after getopts -> args stay in $@
# - 'set -e' surprises (ignores some failures); review behaviour

Why it matters

Bash positional + special parameters: \$1/\$@ for args, \$? for exit, \${var:-default} for defaults, string ops for slicing. Strict mode + quote everything + shellcheck = scripts that do not bite. The shapes are small; the discipline saves hours.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
# Inside a script
echo "first: $1  count: $#  all: $@"
Try it Yourself »

Discussion

Loading…