0
0
Bash Scriptingscripting~20 mins

Function arguments ($1, $2 inside function) in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Function Arguments Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
Output of function using positional arguments
What is the output of this Bash script?
Bash Scripting
my_func() {
  echo "First: $1, Second: $2"
}
my_func apple banana
AFirst: , Second:
BFirst: my_func, Second: apple
CFirst: banana, Second: apple
DFirst: apple, Second: banana
Attempts:
2 left
💡 Hint
Remember that $1 and $2 inside a function refer to the function's arguments.
💻 Command Output
intermediate
2:00remaining
Effect of shifting arguments inside a function
What will this script output?
Bash Scripting
my_func() {
  shift
  echo "$1 $2"
}
my_func one two three
Athree
Bone two
Ctwo three
Done three
Attempts:
2 left
💡 Hint
The shift command moves all arguments one position to the left.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in function argument usage
Which option contains a syntax error when trying to print the first argument inside a function?
Bash Scripting
my_func() {
  echo $1
}
my_func test
Aecho $[1]
Becho "$1"
Cecho ${1}
Decho $1
Attempts:
2 left
💡 Hint
Check how positional parameters are referenced in Bash.
🔧 Debug
advanced
2:00remaining
Why does this function print empty values?
Given this script, why does the function print empty lines?
Bash Scripting
my_func() {
  echo "$1 $2"
}
my_func
AFunction syntax is incorrect
BNo arguments were passed, so $1 and $2 are empty
CVariables $1 and $2 are not accessible inside functions
DThe echo command is missing quotes
Attempts:
2 left
💡 Hint
Think about what happens if you call a function without arguments.
🚀 Application
expert
3:00remaining
How to pass all script arguments to a function preserving spaces
You want to pass all arguments given to the script into a function, preserving spaces in each argument. Which option correctly does this?
Bash Scripting
my_func() {
  for arg in "$@"; do
    echo "$arg"
  done
}
# How to call my_func with all script arguments?
Amy_func "$@"
Bmy_func "$*"
Cmy_func $@
Dmy_func $*
Attempts:
2 left
💡 Hint
Use quotes to preserve each argument as a separate word.