4

I've got three bash scripts in three different sibling directories.

The first few lines of each do some setup, different between each one.

The last twenty or so lines of the scripts are character for character identical, processing and comparing the files constructed in the first bit.

What I'd like to do is to put the last twenty lines in, say ../common.bash, and do something like

#include "../common.bash" 

in each of the three scripts, so as to avoid having to make the same changes in three places every time I fiddle.

So far my best guess is to use cat to construct the scripts out of the four morally-independent pieces.

Is there a better way?

John Lawrence Aspden
  • 17,124
  • 11
  • 67
  • 110
  • Make the common aspects into functions define them in scripts and export them as `export -f ` so that you can re-use them in other scripts – Inian May 25 '17 at 14:53
  • 1
    Instead of include why not just put the last 20 lines in a script and then run or source it at the end of the others? – 123 May 25 '17 at 14:56

2 Answers2

6

Use the source.

source /path/to/common.bash

You shouldn't use a relative path, because it will be interpreted relative to the user's working directory, not the location of the script.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks! That path thing is a bit nasty. Is there anyway to say 'one directory up from the location of this file'? Otherwise the thing will break every time it gets moved / renamed / checked out in the wrong place. – John Lawrence Aspden May 25 '17 at 15:34
  • You could put it in a directory that's in `$PATH` and leave out the directory. `source` will search for it. – Barmar May 25 '17 at 15:38
  • See https://stackoverflow.com/questions/59895/getting-the-source-directory-of-a-bash-script-from-within – Barmar May 25 '17 at 15:38
  • @JohnLawrenceAspden `../script`? – 123 May 25 '17 at 15:42
  • 1
    @123 That won't work. It will go up from the user's directory, not the script's directory. – Barmar May 25 '17 at 15:44
  • @Barmar yeah i, probably wrongly, assumed it was going to be run from the same directory they were in. – 123 May 25 '17 at 15:50
-1

Use meld

source is probably the answer I wanted, but actually in this case I've found that it's best to use meld to view the three files side by side, and to use meld to propagate favourite changes.

The advantage is that when working on one file, I can see the whole thing at once.

But it won't scale to the inevitable fourth copy, so at that point I'll use source, I guess.

John Lawrence Aspden
  • 17,124
  • 11
  • 67
  • 110