Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute a relative path shell script from a shell script

Tags:

bash

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?

like image 878
Nick Ginanto Avatar asked Apr 06 '26 21:04

Nick Ginanto


1 Answers

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
like image 82
ErikMD Avatar answered Apr 08 '26 16:04

ErikMD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!