Positional Parameters and shift

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 44 of 205

The variables $1, $2, $3 and so on are called positional parameters, because each one is identified by its position in the argument list. They are not fixed: Bash lets you remove the first one with shift, replace the whole list with set --, and read parts of the list with slices. These tools make it possible to process any number of arguments, however many the user supplies.

What Positional Parameters Are

When a script (or a function) starts, Bash fills the positional parameters from the words that follow its name. Three related values always describe the current list:

  • $1, $2, ... hold the individual arguments.
  • $# holds how many there are.
  • "$@" expands to all of them.

Everything in this lesson changes that list, and $# and "$@" always reflect the change. The previous lessons showed how to read the list. This lesson shows how to modify it.

Removing the First Argument with shift

The shift built-in discards $1, moves every remaining argument one place to the left, and reduces $# by one:

cat > s1.sh <<'EOF'
echo "before: \$1=$1 \$2=$2 \$3=$3 \$#=$#"
shift
echo "after shift: \$1=$1 \$2=$2 \$3=$3 \$#=$#"
shift 2
echo "after shift 2: \$1=[$1] \$#=$#"
EOF
bash s1.sh a b c d
before: $1=a $2=b $3=c $#=4
after shift: $1=b $2=c $3=d $#=3
after shift 2: $1=[d] $#=1

The steps work like this:

  1. The script starts with four arguments: a b c d.
  2. shift removes a. What used to be $2 (b) is now $1, and the count drops to 3.
  3. shift 2 removes two more arguments (b and c). Only d is left, and it is now $1.

A removed argument cannot be recovered through $1, so save any value you still need before shifting. The name of the script in $0 is not part of the list and is never changed by shift.

Shifting Too Far

shift N needs at least N arguments. If you ask for more than exist, nothing is removed and the command returns status 1, silently:

cat > s2.sh <<'EOF'
echo "args: $#"
shift 5
echo "status=$? args now: $#"
shift 0
echo "shift 0: status=$? args now: $#"
EOF
bash s2.sh a b
args: 2
status=1 args now: 2
shift 0: status=0 args now: 2

shift 5 failed and left both arguments in place, while shift 0 is allowed and does nothing. Because a failed shift prints no message, test the count first or check the status when a script depends on it:

cat > s14.sh <<'EOF'
shift 3 2>/dev/null || echo "not enough arguments to shift (status $?)"
EOF
bash s14.sh a
not enough arguments to shift (status 1)

A negative or non-numeric count is an error with a message:

cat > s15.sh <<'EOF'
shift -1
echo "status=$?"
EOF
bash s15.sh a b
s15.sh: line 1: shift: -1: shift count out of range
status=1

Looping Through All Arguments with shift

A loop that repeatedly handles $1 and then shifts is the classic way to process an unknown number of arguments:

cat > s4.sh <<'EOF'
#!/usr/bin/env bash
while (( $# > 0 )); do
  echo "processing: $1 (remaining after this: $(( $# - 1 )))"
  shift
done
echo "done, \$# is $#"
EOF
bash s4.sh alpha beta gamma
processing: alpha (remaining after this: 2)
processing: beta (remaining after this: 1)
processing: gamma (remaining after this: 0)
done, $# is 0

The condition (( $# > 0 )) is true while arguments remain. Each pass handles the current $1 and then shifts it away, so the loop ends when the list is empty.

If you only need to look at each argument and do not need to consume them, for arg in "$@" is simpler, and it leaves the list unchanged:

cat > s12.sh <<'EOF'
for arg in "$@"; do echo "for: $arg"; done
echo "\$# after for loop: $#"
EOF
bash s12.sh p q
for: p
for: q
$# after for loop: 2

Choose the while and shift pattern when the handling of one argument depends on the next one, which happens with options that take a value.

Parsing Options That Take a Value

An option such as -o out.txt consists of two words. The script handles the flag, then shifts once more to skip over the value:

cat > opts.sh <<'EOF'
#!/usr/bin/env bash
verbose=0
output=""
files=()
while [[ $# -gt 0 ]]; do
  case $1 in
    -v|--verbose)
      verbose=1
      ;;
    -o|--output)
      if [[ $# -lt 2 ]]; then
        echo "error: $1 needs a value" >&2
        exit 1
      fi
      output=$2
      shift
      ;;
    *)
      files+=("$1")
      ;;
  esac
  shift
done
echo "verbose=$verbose output=${output:-none}"
echo "files (${#files[@]}): ${files[*]}"
EOF
bash opts.sh -v -o out.txt a.txt b.txt
bash opts.sh -o
echo "exit=$?"
verbose=1 output=out.txt
files (2): a.txt b.txt
error: -o needs a value
exit=1

Here is how the first run is processed:

  1. -v matches the first pattern, so verbose becomes 1. The shift at the bottom of the loop removes it.
  2. -o matches the second pattern. The script saves $2 (out.txt) in output, shifts once inside the branch to remove the flag, and the shift at the bottom of the loop removes the value.
  3. a.txt and b.txt match the * pattern and are added to an array of file names.

In the second run, -o was the last argument, so $# was 1 and the guard [[ $# -lt 2 ]] printed an error instead of reading a value that was not there. The case statement is covered later in the tutorial, and getopts offers a ready-made alternative for option parsing.

Taking the First Argument and Passing On the Rest

A frequent task is treating the first argument as a command or sub-command and forwarding everything else. Save the first argument, shift it away, and then use "$@" for the remainder:

cat > run.sh <<'EOF'
#!/usr/bin/env bash
cmd=$1
shift
echo "running: $cmd with $# arguments"
"$cmd" "$@"
echo "exit status: $?"
EOF
bash run.sh printf '[%s]\n' "a b" c
running: printf with 3 arguments
[a b]
[c]
exit status: 0

After shift, "$@" holds the three remaining arguments: the printf format and the values a b and c. The argument a b stayed in one piece because "$@" preserves each argument.

Replacing the List with set --

The set command can also overwrite the positional parameters. Everything after -- becomes the new list:

cat > s6.sh <<'EOF'
echo "initial: $# args: $*"
set -- red green blue
echo "after set --: $# args: $1 $2 $3"
set --
echo "after set -- with nothing: $# args"
set -- $(echo one two three)
echo "from command output: $# args, second=$2"
set -- "a b" c
echo "quoted: $# args, first=[$1]"
EOF
bash s6.sh x y
initial: 2 args: x y
after set --: 3 args: red green blue
after set -- with nothing: 0 args
from command output: 3 args, second=two
quoted: 2 args, first=[a b]

What each line does:

  • set -- red green blue throws away x y and installs three new arguments.
  • set -- with nothing after it empties the list, so $# is 0.
  • set -- $(...) splits the output of a command into words and loads them. Unquoted command output is split on whitespace, so use this form only when that splitting is what you want.
  • Quoting an item ("a b") keeps it as a single argument.

The double dash -- marks the end of the options for set. It matters when a value starts with a dash, because without it set would try to read the value as one of its own options:

cat > s7.sh <<'EOF'
set -- -x -y
echo "with --: $# args: $1 $2"
EOF
bash s7.sh
with --: 2 args: -x -y

Reading Part of the List

"${@:offset}" and "${@:offset:length}" produce a slice of the arguments without changing the list:

cat > s8.sh <<'EOF'
echo "all:            $@"
echo "from 2:         ${@:2}"
echo "2 items from 2: ${@:2:2}"
echo "last:           ${@: -1}"
echo "count after a slice: $(set -- "${@:2}"; echo $#)"
echo "original count still: $#"
EOF
bash s8.sh a b c d e
all:            a b c d e
from 2:         b c d e
2 items from 2: b c
last:           e
count after a slice: 4
original count still: 5

Points to notice:

  • Counting starts at 1, so ${@:2} means "from the second argument to the end".
  • ${@:2:2} takes two items starting at the second.
  • A negative offset counts from the end, but it needs a space after the colon, as in ${@: -1}. Without the space, ${@:-1} would be read as the default-value form :-.
  • The slice inside the $( ... ) was taken in a subshell, so the original list was untouched.
  • The offset 0 includes the script name as the first item, because $0 is treated as position zero.

The last argument can also be fetched with indirect expansion, ${!#}, where # is the argument count and ! means "use that number as the position":

cat > s9.sh <<'EOF'
last=${!#}
echo "last arg: $last"
n=2
echo "argument number $n: ${!n}"
EOF
bash s9.sh first second third
last arg: third
argument number 2: second

The same indirect form, ${!n}, reads the argument whose number is stored in the variable n. This is how you read an argument by a computed position.

Functions Have Their Own Positional Parameters

Each function call gets a fresh list. Shifting inside a function changes only the function's copy:

cat > s10.sh <<'EOF'
f() {
  echo "f start: \$1=$1 \$#=$#"
  shift
  echo "f after shift: \$1=$1 \$#=$#"
}
echo "main: \$1=$1 \$#=$#"
f x y z
echo "main after f: \$1=$1 \$#=$#"
EOF
bash s10.sh m1 m2
main: $1=m1 $#=2
f start: $1=x $#=3
f after shift: $1=y $#=2
main after f: $1=m1 $#=2

The script's own arguments m1 m2 were never touched. The same rule applies to set --:

cat > s11.sh <<'EOF'
f() { set -- changed; echo "in f: $1"; }
f
echo "main: $1"
EOF
bash s11.sh original
in f: changed
main: original

This isolation is what allows functions to be written like small scripts of their own. Lesson 89 returns to passing arguments to functions.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Positional Parameters and shift and get answers drawn from it.

Signed-in readers only.