3

I have 2 bash scripts:

script1.sh
script2.sh

script1.sh

command1
func1(){
}

command2
func2(){
}

I would like to source script1.sh from script2.sh in order to only load the func1() and func2() and not run the commands before or after.

Is there a way to do it?

SuperMak
  • 31
  • 2
  • 2
    Does this answer your question? [Importing functions from a shell script](https://stackoverflow.com/questions/12815774/importing-functions-from-a-shell-script) – Luca Aug 07 '20 at 12:29
  • That would work but the actual script that I want to source is pretty big and has a lot of functions with commands in between them so it would require to add a lot of conditions. I want to avoid changing script1.sh as much as possible. Thanks for the suggestion though! – SuperMak Aug 07 '20 at 12:41
  • 2
    I understand you want to avoid changes in script1, but IMHO the cleanest way is to just extract the functions to a separate file and source it in both your scripts. This will allow you to easily re-use those functions in any of your future scripts as well as having a single, clearly distinguished place for your common functions. – Jiri Valenta Aug 07 '20 at 12:56

1 Answers1

0

Jiri Valenta is 100% correct that they best way to do this is to move all scrip1.sh functions into a separate file, e.g.,

script1_functions.sh # move all functions from script1.sh to here
script1.sh # sources script1_functions.sh and executes commands
script2.sh # sources script1_functions.sh and executes other commands

However, what if script1.sh is outside of your control (e.g., vendor code). In that case, copy-pasting the functions into script2.sh seems like a good idea. However, script1.sh might get modified in the future (a safe assumption), and you might want script2.sh automatically use the modified functions.

But IMO, it's more efficient to work around than to solve this type of problem. Here is an example of such a not-worth-the-trouble solution: get the md5sum of current script1.sh and verify that it is the same at the start of script2.sh. If not, give a warning or error (and maybe abort script2.sh) that script1.sh has changed, so someone needs to review the changes and update either script2.sh code, or script2.sh's md5sum of script1.sh if a code review determines no changes are needed.

webb
  • 4,180
  • 1
  • 17
  • 26