bash include script in another script

 

Reusing previously written scripts/functions is one of the best way to reduce time on writing scripts.

bash also supports reusing of previously written function in another script.

To reuse any script that is previously written in new script we need to use source command.

Source is a command that will “read and execute commands from the fileName argument in the current shell context”.

Here is the example where I am including function.sh script in test.sh:

First I am writing small function in function.sh script just to print argument passed to it. Following is content in function.sh script:

print_args() {

  echo "Arguments for print_args function are $*"

Next I am including function.sh script in test.sh with source command. Following is content in test.sh script:

source ./function.sh #Its always suggested to give absolute path of included script

print_args 123 abc 098 xyz

Output:

Arguments for print_args function are 123 abc 098 xyz

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s