3

I have run.sh script in a directory. I have also two scripts called d1.sh and d2.sh located in it's subdirectory called deep. I want to source both d1.sh and d2.sh in run.sh script, so I can use "test" function stored in d2.sh.

code of run.sh looks like this:

#!/bin/bash

source ./deep/*

test

d1.sh:

#!/bin/bash

echo -e "d1 is loaded"

d2.sh:

#!/bin/bash

echo -e "d2 is loaded"

test() {
    echo -e "test passed!"
}

I execute run.sh with command:

bash run.sh

I get output:

d1 is loaded

So it looks like d1.sh script is loading, but d2.sh not. My question is, why is this happening and how should I do it to load all scripts stored in ./deep folder?

s-kaczmarek
  • 161
  • 1
  • 13
  • 1
    `source` only takes sources one script. The rest of the arguments are passed to the script. So it will only source the first script it sees and treat all the other filenames as arguments to the first script. Use a loop or source each script individually. – Munir May 22 '18 at 19:06

1 Answers1

7

Try this,

#!/bin/bash

for file in ./deep/*;
  do
      source $file;
 done
Eby Jacob
  • 1,418
  • 1
  • 10
  • 28
  • Works like charm! Could you please tell me how can I do the same trick for two folders? Lets say I have folder ./deep and ./deeper Do I have to make two loops or can I use one to do it and store paths in array or something? – s-kaczmarek May 22 '18 at 19:11
  • 1
    You can find all the files ending with sh in all directories of the current folder and then source them, script follows, `for file in $(find . -type f -name "*.sh"); do source $file; done – Eby Jacob May 22 '18 at 19:14