IMC!


Contents


Photos

 







Browsing around...
News  News Links  Links Blog  Blog Italiano  Español 
10 - Creating functions in the bash

 | 

As in many programming languages, also in the bash scripts it's possible to create functions that can repeat many times code blocks. The syntax for creating these functions is:

function name()
{
  function_code
}

or

function function_name()
{
  function_code
}

As you can note, the function word is optional.

Also the brackets at the end of the function name is optional; indeed, differently from many other programming languages, in the bash scripts all the variables have a global scope. Here is an example:

#!/bin/bash

# This script shows that all the variables are global.
# The program prints out "Function", and not "Main program",
# as it usually happens in C programming language.

function change_variable
{
  variable="Function"
}

# Main
variable="Main program"
change_variable
echo "Variable was last modified by: $variable"
 

To make the variable local, that is to avoid that a variable value is modified in the main program, you can use the command local. Looking back at the previous example:

#!/bin/bash

# This script shows how to make local a variable inside a function
# The program prints "Main Program" and not "Function, as it happens
# usually in bash scripting, where variables in functions and main
# program are global unless differently specified.

function change_variable
{
  local variable="Function"
}

# Main
variable="Main program"
change_variable
echo "Variable was last modified by: $variable"
 

You can also pass variables to a function by command line parameters, as the following example shows:

#!/bin/bash

# In this example the values 2 and 4 are passed to
# the function through the command line parameters.
function my_function
{
  var1=$1
  var2=$2
  echo "Passed values: $var1 e $var2"
}

my_function 2 4

 


 | 







Comments

No comment present!

Write a comment

You can write here a comment to the article you've just read. Smiles, links and images are not allowed. The maximum comment length is 4000 characters. Please be polite, all the offensive messages will be deleted.

Your comment (lascia bianco!):
Uses (max 25 characters, required)
Web site (max 255 characters, optional)
e-Mail (max 255 characters, optional, will not be published) Your opinion (lascia bianco!):
Comment (max 4000 characters, required):





Valid HTML 4.01 Transitional
E-Mail - 114.98 ms

Valid HTML 4.01 Transitional