Hacker News new | ask | show | jobs
by TeeMassive 641 days ago
I'd add, in each my Bash scripts I add this line to get the script's current directory:

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

This is based on this SA's answer: https://stackoverflow.com/questions/59895/how-do-i-get-the-d...

I never got why Bash doesn't have a reliable "this file's path" feature and why people always take the current working directory for granted!

2 comments

I like:

    readonly SCRIPT_SRC="$(dirname "${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}")"
    readonly SCRIPT_DIR="$(cd "${SCRIPT_SRC}" >/dev/null 2>&1 && pwd)"
    readonly SCRIPT_NAME=$(basename "$0")
I've been using

script_dir="$(dirname "$(realpath "$0")")"

Hasn't failed me so far and it's easy enough to remember

Read the answers and comments from the SO threads. It won't always work for other people in other context.