← Back to Bash Course | Chapter 13: Advanced Scripting | Lesson 2 of 7

Positional Parameters and shift

Positional parameters are the individual arguments passed to a script or function, numbered $1, $2, and so on, and shift moves them down so $2 becomes $1.

Basic Positional Parameters

$1, $2, and so on refer to the arguments passed to the script (or the current function), while $0 is always the script's own name and $# is the total count of arguments.

Example: Basic Positional Parameters

bash
#!/bin/bash
set -- alpha beta gamma
echo "script/function name placeholder: $0"
echo "first: $1, second: $2, third: $3"
echo "total arguments: $#"

Shifting Through Arguments

shift removes $1 and renumbers every remaining argument down by one, so the old $2 becomes the new $1. This is the standard way to process an arbitrary-length argument list one item at a time.

Example: Shifting Through Arguments

bash
#!/bin/bash
set -- one two three
while [[ $# -gt 0 ]]; do
    echo "processing: $1"
    shift
done
echo "no arguments left: $#"

Shifting by More Than One

shift N removes the first N positional parameters at once, which is useful when a flag and its value need to be consumed together in a manual argument-parsing loop.

Example: Shifting by More Than One

bash
#!/bin/bash
set -- --name Ada extra1 extra2
if [[ $1 == "--name" ]]; then
    value=$2
    shift 2
fi
echo "parsed name: $value"
echo "remaining: $*"

Positional Parameters Inside Functions

Functions have their own independent set of positional parameters based on how they were called, completely separate from the script's own $1, $2, etc., even though the same $1 syntax is used.

Example: Positional Parameters Inside Functions

bash
#!/bin/bash
show_args() {
    echo "inside function: $1 $2"
}

set -- outer1 outer2
echo "outer script args: $1 $2"
show_args inner1 inner2
echo "outer script args unchanged: $1 $2"
Common Mistakes
  1. Forgetting $0 is the script's own name, not the first argument; the first real argument is $1.
  2. Using $* when "$@" was needed, losing the distinction between separate arguments once word splitting or quoting differs.
  3. Calling shift more times than there are remaining arguments, which is usually harmless but can be a sign of a loop-counting bug.
Chapter Summary
  • $0 is the script name, $1, $2, ... are the actual arguments, and $# is the argument count.
  • shift (or shift N) discards the first (or first N) positional parameters, renumbering the rest.
  • A while [[ $# -gt 0 ]]; do ...; shift; done loop is a standard way to process an unknown number of arguments one at a time.
  • Inside a function, positional parameters refer to the function's own arguments, not the script's.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.