2

Is there a way that a bash script detects the path directory in which it's running? It is like if the script is aware of where is it. In order to use files that are in the same location as the script. I'd like to change the directory to where the Bash Script is.

This Bash script is used to trigger few actions (other python scripts, apps... etc.) but I want to switch the operation directory to his root one.

3
  • @RoVO, well it's not exactly a duplicate because it's on a different site. That said, the answer to that question on StackOverflow is exactly what the OP needs ;) Jan 16, 2019 at 9:56
  • @RoVo yes it is. Jan 16, 2019 at 9:58
  • Considering that OP themselves agreed the post is duplicate, it's closed now. However, if necessary this can be reopened. Just let us know Jan 16, 2019 at 10:51

1 Answer 1

1

The $PWD variable (which is also queried by pwd command) will tell you current working directory where the shell script operates. However, finding where the script itself is located depends on couple factors.

If you are using bash shell, you may use ${BASH_SOURCE[0]} variable for the purpose of finding where the script runs, as shown by Dave Dopson:

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

In other cases, such as zsh (unless in a function), ksh, and POSIX /bin/sh the $0 variable should be queried, probably with the use of dirname command, or via parameter substitution. Note that this applies mostly to the top-level scripts that you execute.

However, sourced scripts can be a problem, if you're not using bash and ${BASH_SOURCE[0]} variable. According to Gilles's answer, location of sourced scripts is not available in general from within the script itself. The calling script will know the location, but the sourced script - won't. However, the cited answer by Gilles offers a few solutions. There are a few ways to portably determine if the script is sourced, however it seems the only benefit of that is to determine that script location is not available.

Not the answer you're looking for? Browse other questions tagged .