0

I wonder if there's a good way to source another shell script without $(basename "$0") solution, since sometimes "$0" is not set.

For exmaple "$0" would be "-sh" for login shell.

There's same problem with regard to cwd solution.

Vertexwahn
  • 7,709
  • 6
  • 64
  • 90
A.Stone
  • 137
  • 1
  • 9

1 Answers1

3

You could use this expression to find out the directory of the parent Bash script:

dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

Then you can call your script like this:

cd $dir; source ./other_script

or

source $dir/other_script

See this related post: Getting the source directory of a Bash script from within

Community
  • 1
  • 1
codeforester
  • 39,467
  • 16
  • 112
  • 140
  • What about non-bash solution? Is there a POSIX shell solutions? – A.Stone Jan 18 '17 at 20:08
  • I didn't find a POSIX solution. If I were to do it, I will check the output of `$(dirname $0)`. If it is an absolute path, just use that dir. If it is a relative path, use `$PWD/$(dirname $0)`. Otherwise, traverse `$PATH` and look for `$0` in each directory. – codeforester Jan 18 '17 at 20:14
  • This still won't work, as sometimes $0 is the -sh, which is irrelevant to any path. – A.Stone Jan 18 '17 at 20:23
  • 1
    That could be simplified into `dir="${BASH_SOURCE[0]%/*}"`, which removes the external call to dirname as well as the two subshells this answer creates. – Adam Katz Jan 19 '17 at 18:04