4

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
  • 15,966
  • 8
  • 49
  • 55
KodeFor.Me
  • 13,069
  • 27
  • 98
  • 166

2 Answers2

13

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
  • 15,966
  • 8
  • 49
  • 55
  • In theory that looks like it ought to work. However my output shows "Hello World" twice. Sourcing the script causes the function to execute too. How did you prevent that in your environment? – shawn1874 Feb 02 '23 at 18:38
  • Actually, that was my fault. I had added a call to the sayHello function in my version of the utils.sh and when you source a script it will seem to execute anything that is not encapsulated in a function. To reuse functions it appears to be better to have a script that only has stuff encapsulated in functions. Resusing functions in a script that also has something like "main" code doesn't seem to work well. – shawn1874 Feb 02 '23 at 18:56
4

Your main script should be something like this:

#!/bin/bash

source utils.sh

echo "Main"
sayHello
Arjun Mathew Dan
  • 5,240
  • 1
  • 16
  • 27