Find the answer to your Linux question:
Results 1 to 4 of 4
Dear All, I need a help regarding writing a function in a shell, what exactly a function does!! i am new to scripting so little bit confused!! Regards Keshari...
  1. #1
    Just Joined!
    Join Date
    Sep 2010
    Posts
    3

    Help needed to write a function in a shell script!!

    Dear All,

    I need a help regarding writing a function in a shell, what exactly a function does!!

    i am new to scripting so little bit confused!!

    Regards
    Keshari

  2. #2
    Linux Engineer Freston's Avatar
    Join Date
    Mar 2007
    Location
    The Netherlands
    Posts
    1,047
    Welcome to the forums!

    Basic function form is this:

    Code:
    FunctionName() 
    {
       command1
       command2
       command3
    }
    But you can find a wealth of information in the Advanced Bash-Scripting Guide
    Can't tell an OS by it's GUI

  3. #3
    Just Joined!
    Join Date
    Sep 2010
    Posts
    3

    RE:Help needed to write a function in a shell script!!

    Hi,

    Thanks a lot for your reply.

    Just need one clarification:--

    If i want to write some commands like "grep" "cat".. in a function and i want to call that function, then how i can do that, if possible can you give me one example..


    Regards
    Keshari

  4. #4
    Linux Engineer Freston's Avatar
    Join Date
    Mar 2007
    Location
    The Netherlands
    Posts
    1,047
    Ok, an example



    Code:
    #!/bin/bash
    ExampleFunction()
    {
        # Remember, this is just an example
    
            # Most direct:
    	echo "First:	You've used 'ls' `grep -c ls ~/.bash_history` times"
    
    
    
    	# Adding variable:
    	count=`grep -c ls ~/.bash_history`
    	echo "Second:	You've used 'ls' $count times"
    
    
    
    	# Using a pipe:
    	count=`cat ~/.bash_history | grep -c ls`
    	echo "Third:	You've used 'ls' $count times"
    
    
    
    	# Added whitespace for readability:
    	count=`
    		cat		~/.bash_history	|\
    		grep 		ls		|\
    		wc -l				`
    
    	echo	"Fourth:	You've used 'ls' $count times"
    
    
    }
    
    
    echo "Calling function:"
    ExampleFunction
    As you see, you call a function as if it where a command. And it'll execute whatever is between the brackets { }
    Can't tell an OS by it's GUI

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...