functions in bash

April 20, 2007 · Posted in shell 

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:

 
function example(){
	# do something here
	echo "just an example";
}

or just :

 
example(){
	echo "this is an example";
}

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:

 
function show_params(){
	for i in $@ ; do
		echo $i ;
	done
}
#and now we call the function
show_params  first  second  hello world last

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.

 
#!/bin/bash
function test_return()
{
return 3
}
test_return
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:

a=$(show_params  first  second  hello world last)
  • Twitter
  • Digg
  • Reddit
  • del.icio.us
  • Slashdot
  • StumbleUpon
  • DZone
  • NewsVine
  • Technorati
  • Simpy
  • email
  • Facebook
  • Google Bookmarks
  • Live
  • Sphinn
  • co.mments
  • SphereIt
  • Wikio
  • FSDaily
  • Mixx
  • RSS
  • Tumblr
  • Yahoo! Bookmarks

Comments

Leave a Reply