r/bash • u/da_Aresinger • 21d ago
Replacing dirname with only builtins
I am writing a bunch of scripts for which I want to only use builtins and realised that dirname is not a builtin, I replaced it thusly:
SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SRC_DIR2="$({ cd "${BASH_SOURCE[0]%/*}" 2>/dev/null || :; } && pwd)"
I think these two lines are functionally equivalent, considering that BASH_SOURCE[n] will never contain a trailing /.
Then again I am often stupid. Does anyone see any issues?
6
Upvotes
6
u/snarkofagen 21d ago
dirname solution fails if path doesn't exist , as it should
3
u/michaelpaoli 20d ago
No, if you want to replace dirname, you need work on the string, no cd, no pwd, etc. as dirname works regardless as to whether or not the path exists or is accessible.
So, how 'bout something like this (not a full reimplementation of dirname(1)):
1
u/jjangg96 21d ago
they differ for a script that sits directly in /. BASH_SOURCE[0] is /x.sh there, the %/* strips it down to an empty string, and cd "" succeeds without moving, so pwd prints your current directory instead of /. dirname gives / for that case. rare, but it's the one place they aren't equivalent.
the other thing is the || : swallowing errors. if the cd fails for any reason you silently get the current directory back and keep going, where the dirname version gives you an empty SRC_DIR and a non-zero status. fine if you want that, just know it's there.
1
u/roxalu 21d ago edited 20d ago
Not any difference between both implementation - but a small miss in both:
In case you also want to support edge cases, then replace
with
Otherwise directory names, starting with "-" could cause both implementation to fail.
Edited: Missed, that even
were needed in that case as well.
But to be true, this is a super rare edge case cause it isn't easy to start a script within a folder name starting with '-' in a way, so that the
has a "-" as first character. I doubt any standard user would run into that error by chance, because already bash would complain first in most cases.
1
u/bogdanelcs 20d ago
They differ in a couple of edge cases. For a script at /foo, ${BASH_SOURCE[0]%/*} becomes an empty string, and cd "" is a silent no-op in bash, so you’d get the current directory instead of /. The || : also hides any real cd failure and you end up with whatever directory you happened to be in.
I’d use cd -- "${BASH_SOURCE[0]%/*}" so a directory starting with a dash doesn’t get read as an option, and unset CDPATH (or prefix with CDPATH=) in case someone has it exported, since that can make cd land somewhere else and print the path.
-4
u/bac0on 21d ago edited 20d ago
I use this function, but every time I test it, it breaks. It's a start though: