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:

  1. span style="color: #ff0000;">"just an example";
  2. }

or just :

  1. span style="color: #ff0000;">"this is an example";
  2. }

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:

  1.  

This will output:

first
second
hello
world
last

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

  1.  

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.  

Leave a Reply

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