0
0
Bash Scriptingscripting~5 mins

Shifting arguments (shift) in Bash Scripting

Choose your learning style9 modes available
Introduction

Shifting arguments helps you move through command-line inputs one by one. It makes handling many inputs easier.

When you want to process each command-line argument in order.
When you need to remove the first argument after using it.
When writing scripts that accept a flexible number of inputs.
When looping through all arguments without knowing how many there are.
Syntax
Bash Scripting
shift [n]

shift moves the argument list left by n positions. If n is not given, it shifts by 1.

After shifting, $1 becomes the next argument, $2 becomes the one after, and so on.

Examples
Shifts arguments by 1. $1 is removed, $2 becomes new $1.
Bash Scripting
shift
Shifts arguments by 2. First two arguments are removed.
Bash Scripting
shift 2
Loops through all arguments, printing each, then shifting to the next.
Bash Scripting
while [ "$#" -gt 0 ]; do
  echo "Argument: $1"
  shift
 done
Sample Program

This script prints each argument one by one. It uses shift to move to the next argument until none are left.

Bash Scripting
#!/bin/bash
# Script to show shifting arguments

while [ "$#" -gt 0 ]; do
  echo "Current argument: $1"
  shift
 done
OutputSuccess
Important Notes

If you shift more than the number of arguments, $# becomes 0 and no arguments remain.

Use shift carefully to avoid losing arguments you still need.

Summary

Shift moves command-line arguments left, dropping the first ones.

It helps process arguments one at a time in scripts.

Without a number, shift moves by 1 argument.