Positional parameters pass data into scripts: $0 is the script name, $1… are args, $# is the count, $@ expands to all args.
Positional parameters
#!/usr/bin/env bash
echo "script: $0"
echo "args: $@"
echo "count: $#"
echo "first: ${1:-none}"${1:-none} uses default none if $1 is unset—part of parameter expansion.
shift
while [[ $# -gt 0 ]]; do
echo "arg: $1"
shift
doneshift consumes arguments—common for subcommands like tool build / tool test.
getopts
verbose=0
while getopts "v" opt; do
case $opt in
v) verbose=1 ;;
esac
done
shift $((OPTIND - 1))
echo "verbose=$verbose rest=$@"getopts parses short flags; long options need manual parsing or external tools.
Important interview questions and answers
- Q: $@ vs $*?
A: $@ preserves separate words; $* joins into one string—prefer "$@" when forwarding args. - Q: What is $0?
A: Script name or path used to invoke the script.
Self-check
- Which variable holds argument count?
- What does shift do?
Tip: Forward args with "$@", not $*, when wrapping commands.
Interview prep
- $#?
Number of positional arguments.
- shift?
Removes $1 and shifts others down.