0
0
Bash Scriptingscripting~20 mins

Function libraries (sourcing scripts) in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Function Library Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
What is the output when sourcing a script with a function?
Consider two bash scripts:

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"
AHello, Alice!
Bgreet: command not found
CHello, $1!
DNo output
Attempts:
2 left
💡 Hint
Sourcing a script runs its code in the current shell, making functions available.
📝 Syntax
intermediate
1: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?
Ainclude utils.sh
B. utils.sh
Csource utils.sh
Dimport utils.sh
Attempts:
2 left
💡 Hint
In bash, sourcing can be done with 'source' or a dot.
🔧 Debug
advanced
2:30remaining
Why does the function not get recognized after sourcing?
You have a script 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?
Afunctions.sh has Windows line endings causing sourcing to fail
Bsay_hello function is private and cannot be sourced
Csource command is misspelled
Dsay_hello is not defined because functions.sh is empty
Attempts:
2 left
💡 Hint
Check the file format of the sourced script.
🚀 Application
advanced
2: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 7
Arun mathlib.sh
Bimport mathlib.sh
C. mathlib.sh &
Dsource ./mathlib.sh
Attempts:
2 left
💡 Hint
Use the command that loads functions into the current shell.
🧠 Conceptual
expert
3: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"
AEmpty string
BHello
CMYVAR
DError: MYVAR not defined
Attempts:
2 left
💡 Hint
Sourcing runs the script in the current shell environment.