Challenge - 5 Problems
Function Library Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
What is the output when sourcing a script with a function?
Consider two bash scripts:
lib.sh:
main.sh:
What will be the output when running
lib.sh:
greet() {
echo "Hello, $1!"
}main.sh:
#!/bin/bash source ./lib.sh greet "Alice"
What will be the output when running
bash main.sh?Bash Scripting
lib.sh:
greet() {
echo "Hello, $1!"
}
main.sh:
#!/bin/bash
source ./lib.sh
greet "Alice"Attempts:
2 left
💡 Hint
Sourcing a script runs its code in the current shell, making functions available.
✗ Incorrect
The source command loads the function greet into the current shell. Calling greet with argument "Alice" prints "Hello, Alice!".
📝 Syntax
intermediate1:30remaining
Identify the correct syntax to source a script in bash
Which of the following lines correctly sources a script named
utils.sh in bash?Attempts:
2 left
💡 Hint
In bash, sourcing can be done with 'source' or a dot.
✗ Incorrect
Both 'source utils.sh' and '. utils.sh' are valid to source a script. 'include' and 'import' are not bash commands.
🔧 Debug
advanced2:30remaining
Why does the function not get recognized after sourcing?
You have a script
You run another script:
But you get:
What is the most likely cause?
functions.sh with:say_hello() {
echo "Hi!"
}You run another script:
#!/bin/bash source ./functions.sh say_hello
But you get:
./main.sh: line 3: say_hello: command not found
What is the most likely cause?
Attempts:
2 left
💡 Hint
Check the file format of the sourced script.
✗ Incorrect
If functions.sh has Windows CRLF line endings, sourcing can fail silently causing functions to be undefined.
🚀 Application
advanced2:30remaining
How to use a function library with parameters in bash
You want to create a reusable bash function library
mathlib.sh with a function add that adds two numbers and prints the result. Then you want to use it in calc.sh. Which code in calc.sh correctly uses the function to add 5 and 7?Bash Scripting
mathlib.sh:
add() {
echo $(($1 + $2))
}
calc.sh:
#!/bin/bash
# Fill in the missing line here
add 5 7Attempts:
2 left
💡 Hint
Use the command that loads functions into the current shell.
✗ Incorrect
'source ./mathlib.sh' loads the add function so it can be called with arguments.
🧠 Conceptual
expert3:00remaining
What happens to variables when sourcing a script in bash?
If you source a script
vars.sh that sets MYVAR="Hello", what is the value of MYVAR in your current shell after sourcing?Bash Scripting
vars.sh: MYVAR="Hello" main.sh: #!/bin/bash source ./vars.sh echo "$MYVAR"
Attempts:
2 left
💡 Hint
Sourcing runs the script in the current shell environment.
✗ Incorrect
Variables set in a sourced script become part of the current shell environment and are accessible after sourcing.