Created
September 10, 2025 14:26
-
-
Save glektarssza/0c81b32c7ad70d9c03599b9f9ef5d6c9 to your computer and use it in GitHub Desktop.
Get Script Directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Useful one liner to get the script directory from almost any location. | |
| declare SCRIPT_DIR; | |
| SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"; | |
| # Useful one liner to get the script directory from almost any location. | |
| declare SCRIPT_DIR; | |
| SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; | |
| # Multi-line solution to get the script directory from any location. | |
| declare SCRIPT_SOURCE SCRIPT_DIR; | |
| SCRIPT_SOURCE="${BASH_SOURCE[0]}"; | |
| while [ -h "${SCRIPT_SOURCE}" ]; do | |
| SCRIPT_DIR="$(cd -P "$(dirname "${SCRIPT_SOURCE}")" && pwd)"; | |
| SCRIPT_SOURCE="$(readlink "${SCRIPT_SOURCE}")"; | |
| [[ "${SCRIPT_SOURCE}" != /* ]] && SCRIPT_SOURCE="${SCRIPT_DIR}/${SCRIPT_SOURCE}"; | |
| done | |
| SCRIPT_DIR="$(cd -P "$(dirname "${SCRIPT_SOURCE}")" && pwd)"; | |
| # Multi-line solution to get the script directory from any location wrapped in a function. | |
| function get_script_dir() { | |
| local SOURCE_PATH="${BASH_SOURCE[0]}"; | |
| local SYMLINK_DIR; | |
| local SCRIPT_DIR; | |
| while [ -L "${SOURCE_PATH}" ]; do | |
| SYMLINK_DIR="$(cd -P "$(dirname "${SOURCE_PATH}")" > /dev/null 2>&1 && pwd)"; | |
| SOURCE_PATH="$(readlink "${SOURCE_PATH}")"; | |
| if [[ "${SOURCE_PATH}" != /* ]]; then | |
| SOURCE_PATH="${SYMLINK_DIR}/${SOURCE_PATH}"; | |
| fi | |
| done | |
| SCRIPT_DIR="$(cd -P "$(dirname "${SOURCE_PATH}")" > /dev/null 2>&1 && pwd)"; | |
| echo "${SCRIPT_DIR}"; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment