0
0
Bash Scriptingscripting~20 mins

Function definition in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Bash Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
Output of a simple Bash function call
What is the output of this Bash script?
Bash Scripting
greet() {
  echo "Hello, $1!"
}
greet World
AHello, World!
Bgreet World
CHello, $1!
DWorld
Attempts:
2 left
💡 Hint
Look at how the function uses the first argument $1 inside echo.
💻 Command Output
intermediate
2:00remaining
Return value from a Bash function
What is the output of this Bash script?
Bash Scripting
add() {
  echo $(( $1 + $2 ))
}
result=$(add 3 4)
echo $result
A34
Badd 3 4
C3 4
D7
Attempts:
2 left
💡 Hint
The function echoes the sum of two numbers, which is captured in result.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in this Bash function
Which option contains the correct syntax for defining a Bash function?
Agreet() { echo "Hi" }
Bgreet() echo "Hi"
Cfunction greet() { echo "Hi" }
Dfunction greet { echo "Hi" }
Attempts:
2 left
💡 Hint
A Bash function needs parentheses and braces properly placed.
🔧 Debug
advanced
2:00remaining
Why does this Bash function not print the expected output?
Given this script, what is the reason it prints nothing? myfunc() { local msg="Hello" } myfunc echo $msg
AThe variable msg is local to the function and not visible outside.
BThe function myfunc is never called.
CThe echo command is inside the function but not executed.
DThe variable msg is misspelled.
Attempts:
2 left
💡 Hint
Think about variable scope inside and outside functions.
🚀 Application
expert
3:00remaining
Function to check if a file exists and is readable
Which function definition correctly checks if a file exists and is readable, then prints 'File OK' or 'File missing or unreadable'?
A
check_file() {
  if [[ -r "$1" ]]; then
    echo "File OK"
  else
    echo "File missing or unreadable"
  fi
}
B
check_file() {
  if test -r "$1"; then
    echo "File OK"
  else
    echo "File missing or unreadable"
  fi
}
C
check_file() {
  if [ -f "$1" -a -r "$1" ]; then
    echo "File OK"
  else
    echo "File missing or unreadable"
  fi
}
D
check_file() {
  if [ -e "$1" ] && [ -r "$1" ]; then
    echo "File OK"
  else
    echo "File missing or unreadable"
  fi
}
Attempts:
2 left
💡 Hint
Check both if the file exists and is readable using test operators.