0
0
Bash Scriptingscripting~10 mins

Function arguments ($1, $2 inside function) in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Function arguments ($1, $2 inside function)
Define function
Call function with args
Inside function: $1, $2 hold args
Use $1, $2 in commands
Function ends, return to caller
The function is defined, then called with arguments. Inside, $1 and $2 hold the first and second arguments, used in commands.
Execution Sample
Bash Scripting
greet() {
  echo "Hello, $1 and $2!"
}

greet Alice Bob
Defines a function greet that prints a hello message using two arguments passed when calling it.
Execution Table
StepActionValue of $1Value of $2Output
1Define function greet---
2Call greet with Alice BobAliceBob-
3Inside greet: echo messageAliceBobHello, Alice and Bob!
4Function ends, return to caller---
💡 Function completes after printing the message.
Variable Tracker
VariableStartAfter callInside functionAfter function ends
$1--Alice-
$2--Bob-
Key Moments - 2 Insights
Why does $1 hold 'Alice' inside the function?
Because when the function is called (see execution_table step 2), the first argument 'Alice' is assigned to $1 inside the function.
What happens if the function is called with only one argument?
Then $2 will be empty inside the function, so using $2 will produce no output or an empty string (not shown in this trace).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of $2 at step 3?
AHello
BAlice
CBob
DUndefined
💡 Hint
Check the 'Value of $2' column at step 3 in the execution_table.
At which step does the function greet get called with arguments?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for the step describing the function call in the execution_table.
If we call greet with 'John' only, what will $2 be inside the function?
AEmpty string
BError
CJohn
DUndefined variable
💡 Hint
Refer to key_moments about missing second argument behavior.
Concept Snapshot
Function arguments in bash are accessed inside functions as $1, $2, etc.
$1 is the first argument, $2 the second.
When calling a function, pass arguments separated by spaces.
Inside the function, use $1, $2 to refer to them.
If fewer arguments are passed, missing ones are empty strings.
Full Transcript
This visual trace shows how bash function arguments work. First, a function named greet is defined. Then it is called with two arguments: Alice and Bob. Inside the function, $1 holds 'Alice' and $2 holds 'Bob'. The function uses echo to print a message including these arguments. After printing, the function ends and returns control to the caller. If fewer arguments are passed, the missing ones become empty inside the function. This helps understand how to pass and use arguments in bash functions.