Skip to content

Instantly share code, notes, and snippets.

@motchy869
Created September 16, 2025 13:54
Show Gist options
  • Select an option

  • Save motchy869/0d60fd09eecd43fd5181f7f3f15efded to your computer and use it in GitHub Desktop.

Select an option

Save motchy869/0d60fd09eecd43fd5181f7f3f15efded to your computer and use it in GitHub Desktop.
My Bash functions
# (Generated by GPT-5)
# Returns the directory of a script file, resolving any symlinks,
# and normalizing to the physical path (no symlink components).
# Usage:
# SCRIPT_DIR="$(script_dir)" # when function is defined in the same script
# SCRIPT_DIR="$(script_dir "${BASH_SOURCE[0]}")" # get caller's script dir (recommended if sourced from a lib)
# Notes:
# - Bash only (uses BASH_SOURCE and [[ ]]).
# - Works on macOS and Linux without relying on 'readlink -f'.
# - For process substitution or stdin execution, there may be no real file path.
script_dir() {
local src="${1:-${BASH_SOURCE[0]}}"
# Follow symlinks
while [ -h "$src" ]; do
# Resolve the directory of the current link (physical)
local dir
dir="$(cd -P "$(dirname "$src")" && pwd)" || return
# Read the symlink target (BSD/macOS-compatible; no '-f')
src="$(readlink "$src")" || return
# If the target is relative, make it absolute based on the previous directory
[[ $src != /* ]] && src="$dir/$src"
done
# Return the physical directory of the final real file
cd -P "$(dirname "$src")" && pwd
}
# Variant: write the result directly into a named variable (no subshell needed).
# Usage:
# script_dir_into SCRIPT_DIR # same file
# script_dir_into SCRIPT_DIR "${BASH_SOURCE[0]}" # caller's script (recommended when sourced)
script_dir_into() {
local __var="$1"; shift || true
# Prefer an explicit src when provided; otherwise try the caller's file,
# falling back to this function's file.
local __src="${1:-${BASH_SOURCE[1]:-${BASH_SOURCE[0]}}}"
local __dir
__dir="$(script_dir "$__src")" || return
# Bash 3.1+ (macOS 3.2 is OK): assign without eval
printf -v "$__var" '%s' "$__dir"
}
# example usage:
# SCRIPT_DIR="$(script_dir)"
# echo $SCRIPT_DIR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment