Writing Functions in Shell Script

Have you ever written a huge Unix script and thought you would have divided this script into pieces of reusable code? Well don’t worry. You can create functions in unix shell script and make reusable code and call the function from your unix code.

Hello World Function in Unix shell script

First let us see a simple code snippet for creating hello world function in Unix. Create a shell script file helloworld.sh and paste following code in it and execute it.
#function hello world defined fnHelloWorld() { #print hello world echo "Hello World"; } #calling hello world function fnHelloWorld
Code language: Bash (bash)
Output
$./helloworld.sh Hello World
Code language: Bash (bash)
The above shell script will print Hello World on command prompt. All we have done is we have defined a function in shell script by fnHelloWorld() {} and called this by just fnHelloWorld.

Passing argument to function in shell scripts

Passing argument to the functions in shell script is very easy. Just use $1, $2, .. $n variables that represent arguments in the function. Following is the example of function that takes two argument and prints them. Note that we have called the function fnArgumentFunction and passed two arguments “Hello” and “World” by fnArgumentFunction “Hello” “World”.
fnArgumentFunction() { echo "Argument 1:" . $1 echo "Argument 2:" . $2 } fnArgumentFunction "Hello" "World"
Code language: Bash (bash)
Thus if your function will use three arguments you can just use $1, $2 and $3 in your code. You may want to use $# which gives you number of arguments passed to the function if you want to implement a function with variable arguments.

Returning values from Function in Shell Script

Like passing arguments in function in shell script, returning values are also easy. Following is the example of a function that take two input string and returns the concatenated values. We store the return parameter in a variable and print the variable on screen.
fnReturnFunction() { echo $1$2 } value=$(fnReturnFunction "holly" "wood")
Code language: Bash (bash)
Note that in above example we have called the function by $(fnReturnFunction “holly” “wood”).

View Comments

  • Capturing echoed output is fairly useful, but then obtaining the success or failure of the function can get tricky. I might write it like this:

    myfunc() {
    local var=$1
    eval $var="$2$3"
    }

    This makes it handy to test the return value of a function that might fail:
    if myfunc value "holly" "wood"; then
    echo "$value beckons!"
    else
    echo woe is me
    fi

  • My method suffers from increased need for quoting (say the parameters have spaces, you might need to quote them and escape the quotes before passing to eval), also it won't work if the variable name you pass in is the same name as the local variable used to store the name, ie this is broken:

    myfunc var "holly" "wood"

    I've never run into that problem in real life, but I've been reading about it in the context of lisp macros where its known as variable capture. A workaround would be to prefix local vars with underscores.
    Anyway at this point I tend to think heck this needs porting to perl or python :)

Share
Published by
Viral Patel
Tags: Functions Shell Script Unix Shell Script

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

5 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago