Nick Ginanto
Nick Ginanto

Reputation: 32140

execute a relative path shell script from a shell script

given the following:

# a.sh

source ./stuff/b.sh

and

# b.sh

source ./c.sh

folder structure

- a.sh
- stuff
  - b.sh
  - c.sh

when running a.sh it gives an error ./c.sh: No such file or directory

While I can put absolute path for c, I rather keep it relative since the scripts could run in numerous locations.

Is it possible to do?

Upvotes: 3

Views: 1626

Answers (1)

ErikMD
ErikMD

Reputation: 14743

A portable solution to achieve what you want consists in replacing the contents of file b.sh with:

#!/usr/bin/env bash
# (file b.sh)

srcdir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )

source "$srcdir/c.sh"

As a side remark, note that it is maybe unnecessary to source the files at stake: it is especially useful if you need to export in the ambient shell session the variables defined in c.sh. Otherwise (if you just need to run c.sh as a standalone script) you may want to replace the script above with:

#!/usr/bin/env bash
# (file b.sh)

srcdir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )

"$srcdir/c.sh"

and at the same time:

  • add a shebang such as #!/usr/bin/env bash or #!/bin/bash at the beginning of c.sh
  • set the executable bit of c.sh by doing chmod a+x c.sh

Upvotes: 4

Related Questions