Find the answer to your Linux question:
Results 1 to 3 of 3
Let us say that there is a function named 'func()' inside a script named 'script1.sh'. Now there's another script 'script2.sh' which wants to use this function 'func()'. Is there any ...
  1. #1
    Just Joined!
    Join Date
    Jun 2007
    Location
    India
    Posts
    16

    How to include other functions in the other scripts

    Let us say that there is a function named 'func()' inside a script named 'script1.sh'.
    Now there's another script 'script2.sh' which wants to use this function 'func()'. Is there any way to include this function like we use '#include' in C programming?

    thanks in advance...

  2. #2
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    Yes indeed. Just source that script:
    Code:
    #!/bin/bash
    
    source script1.sh
    
    ... rest of script2.sh ...
    And a live example:
    Code:
    alex@danu ~/test/bash $ cat source_func 
    #!/bin/bash
    
    # @(#)  source_func             Contain a function to be sourced by another script
    
    function halloo
    {
            echo "You gave me $1"
    }
    alex@danu ~/test/bash $ cat use_sourced_func 
    #!/bin/bash
    
    # @(#)  use_sourced_func                Use a function obtained by sourcing another script
    
    source source_func
    
    halloo 'test'
    alex@danu ~/test/bash $ ./use_sourced_func 
    You gave me test
    DISTRO=Arch
    Registered Linux User #388732

  3. #3
    Just Joined!
    Join Date
    Jun 2007
    Location
    India
    Posts
    16
    Thanx a lot cabhan.... !!
    It really worked and saved a lot of my retyping of the same code!!!

Posting Permissions

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