How to get the directory where a Bash script is located from within the script?

Get directory location using Bash

You can get the directory where a Bash script is located from within the script itself by using the following command:

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

This command uses the cd command to change to the directory of the Bash script ("${BASH_SOURCE[0]}"), and then uses pwd to print the current working directory.

Here's a breakdown of the command:

  • "$( dirname "${BASH_SOURCE[0]}" )" gets the directory of the Bash script.
  • cd changes to the directory of the Bash script.
  • pwd gets the current working directory, which is the directory of the Bash script.

After running this command, the $DIR variable will contain the directory where the script is located.

You can also use the dirname command directly to get the directory of the script without using cd or pwd:

DIR=$(dirname "${BASH_SOURCE[0]}")

This command will simply set $DIR to the directory where the script is located.

  1. Dynamic variable names in Bash
  2. How to parse command line arguments in Bash?
  3. Bash and shell script variable capitalization?
  4. Parsing JSON with Unix tools
  5. Command not found error in Bash variable assignment
  6. How to set a variable to the output of a command in Bash?
  7. How to run Bash commands in Python?
  8. Extract filename and extension in Bash?
  9. Looping through the content of a file in Bash