0

I have been working on a few bash scripts lately and I am starting to wonder how larger scripts should be set up.

bash scripts are always run in the current directory, so to use source you need the absolute path of the sourced script.

I saw this post, but it seems too complex for something I expected to be a common use-case.

Is there idiomatic way to source scripts in the same directory as the running script?

Community
  • 1
  • 1
everett1992
  • 2,351
  • 3
  • 27
  • 38
  • 2
    If there were an easy way, the answer in that other question wouldn't be so complicated. Bash scripts aren't usually broken up into so many separate scripts, so it's not usually an issue. – Barmar Nov 03 '13 at 22:42
  • The other question covers a general use case while I just want to source other scripts. I didn't have high hopes, but I thought it was worth asking. – everett1992 Nov 03 '13 at 22:56
  • Don't break you script. If it's too long (over 1000 lines), consider using another language. – gniourf_gniourf Nov 03 '13 at 23:43

2 Answers2

3

You can use dirname and $0 to figure out where the currently running script is located (here doit2.sh is a script in the same directory as the original script):

. $(dirname $0)/doit2.sh
cforbish
  • 8,567
  • 3
  • 28
  • 32
  • Cool. It used to be that $0 only gave you the command as executed, not the full path, at least that's how I remember it. Anyone remember that? – Mike Makuch Nov 04 '13 at 17:11
  • That's what I've been using, but it breaks when you run a symbolic link to the script. – everett1992 Nov 04 '13 at 18:51
2

There are not 36,000 solutions:

1) absolute path :

source /absolute_path/script.sh # sourcing a script
. /absolute_path/script.sh # sourcing a script
/absolute_path/script.sh # executing a script

2) relative path :

./script.sh # when script.sh is in the current directory
./dir/script.sh # when script.sh is in the directory 'dir' which is in the current directory
../script.sh # when script.sh is in the parent directory

And you could use source or . script.sh with relative path too.

3) use alias :

echo "alias script='/absolute_path/script.sh'" >> ~/.bashrc
source ~/.bashrc
script # executing script.sh

4) add to the PATH :

echo "export PATH=$PATH:/absolute_path/script.sh" >> ~/.bashrc
source ~/.bashrc
script.sh # executing script.sh

And to know the difference between sourcing a script and executing a script, see this subject.

Community
  • 1
  • 1
Idriss Neumann
  • 3,760
  • 2
  • 23
  • 32