Introduction
Functions can take inputs to work with different data each time. Using $1, $2 inside a function lets you access these inputs easily.
function_name() {
echo "First argument is $1"
echo "Second argument is $2"
}greet() {
echo "Hello, $1!"
}
greet Aliceadd() {
sum=$(( $1 + $2 ))
echo "Sum is $sum"
}
add 5 7show_args() {
echo "Arg1: $1"
echo "Arg2: $2"
echo "Arg3: $3"
}
show_args one two three#!/bin/bash print_info() { echo "Name: $1" echo "Age: $2" } print_info "John" 30
$1 represent?$1 refers to the first argument passed specifically to that function, not the script.$1 resets to the function's first argument.$1 in function = first function argument [OK]$1 and $2?name() { commands; } or function name { commands; } without parameters in parentheses.$1, $2, not declared in parentheses.greet() {
echo "Hello, $1 and $2!"
}
greet Alice Bobgreet is called with two arguments: Alice and Bob. Inside the function, $1 is Alice and $2 is Bob.sum() {
echo $(($1 + $2))
}
sum 5sum expects two arguments, but only one (5) is passed. So, $2 is empty.$(($1 + $2)) becomes (5 + ), which is invalid syntax causing an error about operand expected.concat that joins two strings passed as arguments with a dash between them. Which function definition correctly does this?- between them.$1-$2 which is exactly the two strings joined by a dash. Others use space, plus, or no separator.Pass the test and this pattern moves unknown