meta data for this page
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revision | |||
| linux:bash:source [2026/05/05 12:16] – niziak | linux:bash:source [2026/10/26 19:23] (current) – niziak | ||
|---|---|---|---|
| Line 9: | Line 9: | ||
| The best is to create setup/ | The best is to create setup/ | ||
| - | Another solutions: | + | Take note of possible problems: |
| + | * '' | ||
| + | * '' | ||
| + | |||
| + | ===== Universal approach ===== | ||
| + | |||
| + | This handles executed, sourced, symlinked and sourced-symlinked files, and always returns an absolute path to the real directory. | ||
| + | |||
| + | <code bash> | ||
| + | src=" | ||
| + | while [ -L " | ||
| + | dir=$(CDPATH= cd -P -- " | ||
| + | src=$(readlink " | ||
| + | case $src in /*) ;; *) src=$dir/ | ||
| + | done | ||
| + | DIR=$(CDPATH= cd -P -- " | ||
| + | </ | ||
| + | |||
| + | |||
| + | ===== Simple and universal. ===== | ||
| + | |||
| + | '' | ||
| + | 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=" | ||
| + | DIR=$(cd -- " | ||
| + | </ | ||
| + | |||
| + | ===== Not recommended approaches ===== | ||
| + | |||
| + | NOTE: Not working well in all scenarios! | ||
| <code bash> | <code bash> | ||
| #!/bin/sh | #!/bin/sh | ||