Shell Scripting / Shell Functions

Returning Values from Functions

This tutorial covers how to return values from Shell Functions. We will learn how to capture results from a function and use them in other parts of our script.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores defining and using reusable functions in shell scripts.

1. Introduction

In this tutorial, we will be focusing on how to return values from Shell Functions. Functions in Shell are a way of packaging code that you will use repeatedly. You can save time by calling these functions instead of writing the same code multiple times. The main goal of this tutorial is to understand how to capture results from a function and use them in other parts of our script.

By the end of this tutorial, you will be able to:

  • Understand the concept of returning values from functions in Shell
  • Write your own functions that return values
  • Use returned values in your script

Prerequisites:
Basic knowledge of Shell scripting is required to follow along with this tutorial.

2. Step-by-Step Guide

In Shell, functions do not directly return values like other programming languages. Instead, they output the result, which can then be captured in a variable.

Let's first understand how to create a simple function in Shell. A Shell function is defined like this:

function_name () {
  # code goes here
}

To return a value from a function, we use the command echo. The echo command is used to print data to the standard output, which we can then capture in a variable.

Here's an example:

get_name () {
  echo "John Doe"
}

name=$(get_name)
echo $name  # This will print: John Doe

In this example, the get_name function outputs "John Doe", which is then captured in the name variable.

3. Code Examples

Let's look at a few more practical examples:

Example 1: Function that returns the sum of two numbers

# Function definition
sum () {
  local num1=$1  # The first argument to the function
  local num2=$2  # The second argument to the function
  echo $((num1 + num2))  # The sum of the two numbers
}

# Using the function
result=$(sum 5 3)
echo $result  # This will print: 8

Example 2: Function that checks if a number is even or odd

# Function definition
is_even () {
  local num=$1
  if (( num % 2 == 0 )); then
    echo "even"
  else
    echo "odd"
  fi
}

# Using the function
result=$(is_even 7)
echo $result  # This will print: odd

4. Summary

In this tutorial, we have covered how to return values from Shell functions. We learned that functions in Shell output the result, which can then be captured in a variable using the echo command. We also looked at several examples of functions that return values.

For further learning, you can explore how to use functions with different types of arguments and how to handle errors in functions.

5. Practice Exercises

  1. Write a function that takes a string as an argument and returns the length of the string.
  2. Write a function that takes two numbers as arguments and returns the bigger number.

Solutions

length_of_string () {
  local str=$1
  echo ${#str}
}

result=$(length_of_string "Hello, World!")
echo $result  # This will print: 13
bigger_number () {
  local num1=$1
  local num2=$2
  if (( num1 > num2 )); then
    echo $num1
  else
    echo $num2
  fi
}

result=$(bigger_number 5 9)
echo $result  # This will print: 9

Remember, practice is key to improving your programming skills. Try to come up with your own examples and use cases for functions that return values.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Backlink Checker

Analyze and validate backlinks.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help