functions in bash


Thanks for visiting! If you're new here, you may want to subscribe to my RSS feed. This blog posts regular information about web development, unix/linux, How-tos and patches. Go ahead, subscribe to my feed! You can also receive updates via email, instant messenger, skype or tweeter.

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)
  • Digg
  • Reddit
  • del.icio.us
  • Slashdot
  • Spurl
  • StumbleUpon
  • Furl
  • description
  • Netscape
  • NewsVine
  • Technorati
  • YahooMyWeb
  • Simpy
If you enjoyed this post, you should subscribe to my full RSS Feeds

close Reblog this comment
blog comments powered by Disqus

Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License

Technology Blogs - Blog Top Sites Search For Blogs, Submit Blogs, The Ultimate Blog Directory Blogarama - The Blog Directory 5starsblog Computers Blogs - Blog Flare blog search directory gob BlogHop