Results 1 to 2 of 2

Thread: BASH Programming Functions

  1. #1
    Join Date
    Mar 2008
    Posts
    264

    BASH Programming Functions

    As in almost any programming language, you can use functions to group pieces of code in a more logical way or practice the divine art of recursion.

    Declaring a function is just a matter of writing function my_func { my_code }.

    Calling a function is just like calling another program, you just write its name.

    Eg.

    Code:
     #!/bin/bash 
               function quit {
                   exit
               }
               function hello {
                   echo Hello!
               }
               hello
               quit
               echo foo

    Lines 2-4 contain the 'quit' function. Lines 5-7 contain the 'hello' function If you are not absolutely sure about what this script does, please try it!.

    Notice that a functions don't need to be declared in any specific order.

    When running the script you'll notice that first: the function 'hello' is called, second the 'quit' function, and the program never reaches line 10.

  2. #2
    Join Date
    Mar 2008
    Posts
    264

    Re: BASH Programming Functions

    Functions with parameters

    Code:
    #!/bin/bash 
                    function quit {
                       exit
                    }  
                    function e {
                        echo $1 
                    }  
                    e Hello
                    e World
                    quit
                    echo foo
    This script is almost identically to the previous one. The main difference is the funcion 'e'. This function, prints the first argument it receives. Arguments, within funtions, are treated in the same manner as arguments given to the script.

Similar Threads

  1. Problems with object-oriented programming, classes, objects, functions
    By Lakshmigopal in forum Software Development
    Replies: 5
    Last Post: 04-12-2010, 11:01 AM
  2. Socket programming: Is any new Programming Language?
    By Kushan in forum Software Development
    Replies: 3
    Last Post: 14-11-2009, 11:13 AM
  3. Double Ampersand in bash script programming
    By KuNaLBuntU in forum Software Development
    Replies: 3
    Last Post: 20-08-2009, 05:43 PM
  4. Bash script if then else help
    By Unix'EM in forum Software Development
    Replies: 3
    Last Post: 18-08-2009, 06:34 PM
  5. Replies: 3
    Last Post: 13-12-2008, 01:49 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,714,022,285.35718 seconds with 16 queries