0
0
Bash Scriptingscripting~15 mins

Return values (return and echo) in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Return values with return and echo in Bash
📖 Scenario: You are writing a small Bash script to calculate the sum of two numbers. You want to learn how to get values back from functions using return and echo.
🎯 Goal: Build a Bash script with a function that adds two numbers and returns the result using both return and echo. Then, display the results.
📋 What You'll Learn
Create a function called add_numbers that takes two arguments
Use return to send back the sum modulo 256
Use echo to print the full sum
Call the function and capture both the return value and the echoed output
Print both captured values clearly
💡 Why This Matters
🌍 Real World
In real scripts, functions often need to send back status codes and data. Understanding how <code>return</code> and <code>echo</code> work helps you write better Bash scripts.
💼 Career
Many automation and DevOps tasks use Bash scripts. Knowing how to get values from functions is essential for debugging and building reliable scripts.
Progress0 / 4 steps
1
Create the add_numbers function
Write a Bash function called add_numbers that takes two arguments named num1 and num2. Inside the function, calculate the sum of num1 and num2 and store it in a variable called sum.
Bash Scripting
Need a hint?

Use $1 and $2 to get the function arguments.

2
Add return and echo to the function
Inside the add_numbers function, add a return statement that returns sum % 256. Then, use echo to print the full sum.
Bash Scripting
Need a hint?

Remember return can only return numbers 0-255. Use modulo % 256.

3
Call the function and capture the return value
Call the add_numbers function with arguments 100 and 200. Capture the return value in a variable called ret_val using $? immediately after the call.
Bash Scripting
Need a hint?

Use $? right after the function call to get the return value.

4
Capture the echoed output and print both results
Call add_numbers with 100 and 200 again, but this time capture the echoed output in a variable called echoed_sum using command substitution. Then, print both ret_val and echoed_sum with clear messages.
Bash Scripting
Need a hint?

Use $( ) to capture the echoed output. Use echo to print messages.