functions in bash

When programming/scripting in shell, like in most of the other programing languages you can organize your code in functions that can be called from anywhere in your code, you can pass parameters to them and they can return a value or output something.

A simple function definition would look like this:

  2. function example(){
  3. # do something here
  4. echo "just an example";
  5. }

or just :

  2. example(){
  3. echo "this is an example";
  4. }

If you want your function to have parameters you don't have to put them into your function's prototype. You can access the parameters passed to your function using some special variables $1, $2 ... $n, where $1 is the first parameter passed to your function, $2 is the second and $n is the n'th parameter .If you want a list of all parameters separated by spaces you can get it from the $@ variable.
the next function will just echo all of the parameters passed to it, each one on a single line:

  2. function show_params(){
  3. for i in $@ ; do
  4. echo $i ;
  5. done
  6. }
  7. #and now we call the function
  8. show_params first second hello world last

This will output:


A function can only return a numeric 8 bit positive value between 0 and 255, and that value can be accessed in the $? variable.

  2. #!/bin/bash
  3. function test_return()
  4. {
  5. return 3
  6. }
  7. test_return
  8. echo $?

If you want to return strings you can just echo the strings in the function and then capture the output in a variable like this:

  1. a=$(show_params first second hello world last)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.