3

I have write a script, and I like to now to make it better readable, by moving parts of my main script in other files, but unfortunately I cannot.

Let's say now I have the following code in file utils.sh:

#!/bin/bash

sayHello ()
{
   echo "Hello World"
}

Them from my main script I try the following, but doesn't work:

#!/bin/bash

./utils.sh

sayHello

So, the question is, how to call the functions from within the utils.sh ?

fredtantini
  • 14,608
  • 7
  • 46
  • 54
KodeFor.Me
  • 12,429
  • 26
  • 92
  • 160

2 Answers2

12

You have to source it, with . or source:

~$ cat >main.sh
#!/bin/bash
. ./utils.sh #or source ./utils.sh
sayHello

And then

~$ ./main.sh
Hello World
fredtantini
  • 14,608
  • 7
  • 46
  • 54
4

Your main script should be something like this:

#!/bin/bash

source utils.sh

echo "Main"
sayHello
Arjun Mathew Dan
  • 5,125
  • 1
  • 15
  • 27