meta data for this page
  •  

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
linux:bash:source [2026/05/05 12:16] – niziaklinux:bash:source [2026/10/26 19:23] (current) – niziak
Line 9: Line 9:
 The best is to create setup/installer script which hardcode path to one shared script. The best is to create setup/installer script which hardcode path to one shared script.
  
-Another solutions:+Take note of possible problems: 
 +  * ''readlink -f'' is non-POSIX 
 +  * ''pwd -P'': Resolves physical directory paths, stepping out of symbolic structures. 
 + 
 +===== Universal approach ===== 
 + 
 +This handles executed, sourced, symlinked and sourced-symlinked files, and always returns an absolute path to the real directory. 
 + 
 +<code bash> 
 +src="${BASH_SOURCE[0]}" 
 +while [ -L "$src" ]; do 
 +  dir=$(CDPATH= cd -P -- "$(dirname -- "$src")" && pwd) 
 +  src=$(readlink "$src") 
 +  case $src in /*) ;; *) src=$dir/$src ;; esac   # relative link target 
 +done 
 +DIR=$(CDPATH= cd -P -- "$(dirname -- "$src")" && pwd) 
 +</code> 
 + 
 + 
 +===== Simple and universal. ===== 
 + 
 +''readlink -f'' follows the whole symlink chain itself (nested links, relative targets, symlinked directories),  
 +so no loop is needed. It works on any Linux (GNU coreutils, BusyBox) and on macOS 12.3+. 
 +It also works for sourced files, because BASH_SOURCE[0] is the sourced file’s own path, 
 +which covers the sourced-and-symlinked case. 
 + 
 +<code bash> 
 +src="${BASH_SOURCE[0]}" 
 +DIR=$(cd -- "$(dirname -- "$(readlink -f -- "$src")")" && pwd) 
 +</code> 
 + 
 +===== Not recommended approaches ===== 
 + 
 +NOTE: Not working well in all scenarios! 
 <code bash> <code bash>
 #!/bin/sh #!/bin/sh