0
0
Bash Scriptingscripting~5 mins

Shifting arguments (shift) in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the shift command do in a bash script?
The shift command moves all the positional parameters to the left by one. This means $2 becomes $1, $3 becomes $2, and so on. It helps process arguments one by one.
Click to reveal answer
intermediate
How do you shift by more than one argument at a time?
You can pass a number to shift, like shift 2, to move the positional parameters left by that many places at once.
Click to reveal answer
intermediate
What happens if you shift more times than the number of arguments?
If you shift more than the number of arguments, the positional parameters become empty. Trying to access them will give empty values.
Click to reveal answer
beginner
Why is shift useful in scripts that process command-line arguments?
It lets you handle each argument one at a time in a loop. After processing $1, you use shift to move to the next argument easily.
Click to reveal answer
beginner
Example: What will be the output of this script?<br>
#!/bin/bash
while [ "$#" -gt 0 ]; do
  echo "Argument: $1"
  shift
 done
The script prints each argument on its own line, one by one, until no arguments remain. For example, if run as ./script.sh apple banana cherry, it outputs:<br>Argument: apple Argument: banana Argument: cherry
Click to reveal answer
What does shift do in a bash script?
APrints all arguments
BDeletes all arguments
CMoves positional parameters left by one
DReverses the order of arguments
How do you shift by two arguments at once?
Ashift 2
Bshift -2
Cshift twice
Dshift --two
What happens if you shift more times than the number of arguments?
AScript crashes
BPositional parameters become empty
CArguments repeat
DNothing changes
Why use shift in a loop processing arguments?
ATo count arguments
BTo skip arguments
CTo print arguments backwards
DTo process arguments one by one
If a script starts with $1 = apple and runs shift, what is $1 now?
AThe original $2
Bapple
Cempty
DThe original $3
Explain how the shift command helps in processing command-line arguments in bash scripts.
Think about how you can handle each argument step-by-step.
You got /4 concepts.
    Describe what happens when you use shift 3 in a script with five arguments.
    Consider how the numbering of arguments changes after shifting.
    You got /4 concepts.