I have the following code in my bash script. Now I wanna use it in POSIX sh. How can I convert it?
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" > /dev/null && pwd )"
I have the following code in my bash script. Now I wanna use it in POSIX sh. How can I convert it?
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" > /dev/null && pwd )"
The POSIX-shell (sh
) counterpart of $BASH_SOURCE
is $0
. see bottom for background info
Caveat: The crucial difference is that if your script is being sourced (loaded into the current shell with .
), the snippets below will not work properly. explanation further below
Note that I've changed DIR
to dir
in the snippets below, because it's better not to use all-uppercase variable names so as to avoid clashes with environment variables and special shell variables.
The CDPATH=
prefix takes the place of > /dev/null
in the original command: $CDPATH
is set to a null string so as to ensure that cd
never echoes anything.
In the simplest case, this will do (the equivalent of the OP's command):
dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
If you also want to resolve the resulting directory path to its ultimate target in case the directory and/or its components are symlinks, add -P
to the pwd
command:
dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
Caveat: This is NOT the same as finding the script's own true directory of origin:
Let's say your script foo
is symlinked to /usr/local/bin/foo
in the $PATH
, but its true path is /foodir/bin/foo
.
The above will still report /usr/local/bin
, because the symlink resolution (-P
) is applied to the directory, /usr/local/bin
, rather than to the script itself.
To find the script's own true directory of origin, you'd have to inspect the script's path to see if it's a symlink and, if so, follow the (chain of) symlinks to the ultimate target file, and then extract the directory path from the target file's canonical path.
GNU's readlink -f
(better: readlink -e
) could do that for you, but readlink
is not a POSIX utility.
While BSD platforms, including macOS, have a readlink
utility too, on macOS it doesn't support -f
's functionality. That said, to show how simple the task becomes if readlink -f
is available: dir=$(dirname "$(readlink -f -- "$0")")
.
In fact, there is no POSIX utility for resolving file symlinks. There are ways to work around that, but they're cumbersome and not fully robust:
The following, POSIX-compliant shell function implements what GNU's readlink -e
does and is a reasonably robust solution that only fails in two rare edge cases:
->
(also rare)With this function, named rreadlink
, defined, the following determines the script's true directory path of origin:
dir=$(dirname -- "$(rreadlink "$0")")
Note: If you're willing to assume the presence of a (non-POSIX) readlink
utility - which would cover macOS, FreeBSD and Linux - a similar, but simpler solution can be found in this answer to a related question.
rreadlink()
source code - place before calls to it in scripts:
rreadlink() ( # Execute the function in a *subshell* to localize variables and the effect of `cd`.
target=$1 fname= targetDir= CDPATH=
# Try to make the execution environment as predictable as possible:
# All commands below are invoked via `command`, so we must make sure that `command`
# itself is not redefined as an alias or shell function.
# (Note that command is too inconsistent across shells, so we don't use it.)
# `command` is a *builtin* in bash, dash, ksh, zsh, and some platforms do not even have
# an external utility version of it (e.g, Ubuntu).
# `command` bypasses aliases and shell functions and also finds builtins
# in bash, dash, and ksh. In zsh, option POSIX_BUILTINS must be turned on for that
# to happen.
{ \unalias command; \unset -f command; } >/dev/null 2>&1
[ -n "$ZSH_VERSION" ] && options[POSIX_BUILTINS]=on # make zsh find *builtins* with `command` too.
while :; do # Resolve potential symlinks until the ultimate target is found.
[ -L "$target" ] || [ -e "$target" ] || { command printf '%s\n' "ERROR: '$target' does not exist." >&2; return 1; }
command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
fname=$(command basename -- "$target") # Extract filename.
[ "$fname" = '/' ] && fname='' # !! curiously, `basename /` returns '/'
if [ -L "$fname" ]; then
# Extract [next] target path, which may be defined
# *relative* to the symlink's own directory.
# Note: We parse `ls -l` output to find the symlink target
# which is the only POSIX-compliant, albeit somewhat fragile, way.
target=$(command ls -l "$fname")
target=${target#* -> }
continue # Resolve [next] symlink target.
fi
break # Ultimate target reached.
done
targetDir=$(command pwd -P) # Get canonical dir. path
# Output the ultimate target's canonical path.
# Note that we manually resolve paths ending in /. and /.. to make sure we have a normalized path.
if [ "$fname" = '.' ]; then
command printf '%s\n' "${targetDir%/}"
elif [ "$fname" = '..' ]; then
# Caveat: something like /var/.. will resolve to /private (assuming /var@ -> /private/var), i.e. the '..' is applied
# AFTER canonicalization.
command printf '%s\n' "$(command dirname -- "${targetDir}")"
else
command printf '%s\n' "${targetDir%/}/$fname"
fi
)
To be robust and predictable, the function uses command
to ensure that only shell builtins or external utilities are called (ignores overloads in the forms of aliases and functions).
It's been tested in recent versions of the following shells: bash
, dash
, ksh
, zsh
.
tl;dr:
Using POSIX features only:
You cannot determine the script's path in a sourced invocation (except in zsh
, which, however, doesn't usually act as sh
).
You can detect whether or not your script is being sourced ONLY if your script is being sourced directly by the shell (such as in a shell profile/initialization file; possibly via a chain of sourcings), by comparing $0
to the shell executable name/path (except in zsh
, where, as noted $0
is truly the current script's path). By contrast (except in zsh
), a script being sourced from another script that itself was directly invoked, contains that script's path in $0
.
To solve these problems, bash
, ksh
, and zsh
have nonstandard features that do allow determining the actual script path even in sourced scenarios and also detecting whether a script is being sourced or not; for instance, in bash
, $BASH_SOURCE
always contains the running script's path, whether it's being sourced or not, and [[ $0 != "$BASH_SOURCE" ]]
can be used to test whether the script is being sourced.
To show why this cannot be done, let's analyze the command from Walter A's answer:
# NOT recommended - see discussion below.
DIR=$( cd -P -- "$(dirname -- "$(command -v -- "$0")")" && pwd -P )
-P
twice is redundant - it's sufficient to use it with pwd
.cd
's potential stdout output, if $CDPATH
happens to be set.)command -v -- "$0"
command -v -- "$0"
is designed to cover one additional scenario: if the script is being sourced from an interactive shell, $0
typically contains the mere filename of the shell executable (sh
), in which case dirname
would simply return .
(because that's what dirname
invariably does when given a argument without a path component).
command -v -- "$0"
then returns that shell's absolute path through a $PATH
lookup (/bin/sh
). Note, however, that login shells on some platforms (e.g., OSX) have their filename prefixed with -
in $0
(-sh
), in which case command -v -- "$0"
doesn't work as intended (returns an empty string).command -v -- "$0"
can misbehave in two non-sourced scenarios in which the shell executable, sh
, is directly invoked, with the script as an argument:
command -v -- "$0"
may return an empty string, depending on what specific shell acts as sh
on a given system: bash
, ksh
, and zsh
return an empty string; only dash
echoes $0
command
doesn't explicitly say whether command -v
, when applied to a filesystem path, should only return executable files - which is what bash
, ksh
, and zsh
do - but you can argue that it is implied by the very purpose of command
; curiously, dash
, which is usually the most compliant POSIX citizen, is deviating from the standard here. By contrast, ksh
is the lone model citizen here, because it is the only one that reports executable files only and reports them with an absolute (albeit not normalized) path, as the spec requires.$PATH
, and the invocation uses its mere filename (e.g., sh myScript
), command -v -- "$0"
will also return the empty string, except in dash
.$0
then doesn't contain that information (except in zsh
, which doesn't usually act as sh
) - there's no good solution to this problem.
$0
directly: [ "$0" = "sh" ] || [ "$0" = "-sh" ] || [ "$0" = "/bin/sh" ]
$0
then simply contains the sourcing script's path.command -v -- "$0"
in sourced scenarios and the fact that it breaks two non-sourced scenarios, my vote is for NOT using it, which leaves us with:
$dir
ends up either containing .
, if the shell executable was invoked as a mere filename (applying dirname
to a mere filename always returns .
), or the shell executable's directory path otherwise. .
cannot be reliably distinguished from a non-sourced invocation from the current directory.$0
contains that script's path, and the script being sourced has no way of telling whether that's the case.POSIX defines the behavior of $0
with respect to shell scripts here.
Essentially, $0
should reflect the path of the script file as specified, which implies:
Do NOT rely on $0
containing an absolute path.
$0
contains an absolute path only if:
you explicitly specify an absolute path; e.g.:
~/bin/myScript
(assuming the script itself is executable)sh ~/bin/myScript
you invoke an executable script by mere filename, which requires that it both be executable and in the $PATH
; behind the scenes, the system transforms myScript
into an absolute path and then executes it; e.g.:
myScript # executes /home/jdoe/bin/myScript, for instance
In all other cases, $0
will reflect the script path as specified:
sh
with a script, this can be a mere filename (e.g., sh myScript
) or a relative path (e.g., sh ./myScript
)./myScript
- note that a mere filename would only find scripts in the $PATH
).In practice, bash
, dash
, ksh
, and zsh
all exhibit this behavior.
By contrast, POSIX does NOT mandate the value of $0
when sourcing a script (using the special built-in utility .
("dot")), so you cannot rely on it, and, in practice, behavior differs across shells.
$0
when your script is being sourced and expect standardized behavior.
bash
, dash
, and ksh
leave $0
untouched when sourcing scripts, meaning that $0
contains the caller's $0
value, or, more accurately, the $0
value of the most recent caller in the call chain that hasn't been sourced itself; thus, $0
may point either to the shell's executable or to the path of another (directly invoked) script that sourced the current one.zsh
, as the lone dissenter, actually does report the current script's path in $0
. Conversely, $0
will provide no indication as to whether the script is being sourced or not.$0
to the current script's path is.bash
, ksh
, and zsh
all offer their own ways of obtaining the running script's path, even when it's being sourced.For the sake of completeness: the value of $0
in other contexts:
$0
remain unchanged; therefore, whatever value it has outside the function, it'll have inside as well.
bash
, dash
, and ksh
do behave that way.zsh
is the lone dissenter and reports the function's name.-c
option on startup, it's the first operand (non-option argument) that sets $0
; e.g.:
sh -c 'echo \$0: $0 \$1: $1' foo one # -> '$0: foo $1: one'
bash
, dash
, ksh
, and zsh
all behave that way.$0
is the value of the first argument that the shell's parent process passed - typically, that's the shell's name or path (e.g. sh
, or /bin/sh
); this includes:
-
to the shell name before placing it in $0
, so as to signal to the shell that it is a _login shell; thus, by default, $0
reports -bash
, not bash
, in interactive shells on OSX.sh < myScript
)bash
, dash
, ksh
, and zsh
all behave that way.readlink
utility; given that macOS, FreeBSD and Linux all have this utility, it is a pragmatic and simpler alternative that may work for many. –
Suwannee command cd "$(command dirname -- "$target")"
located inside the while
loop, emits some unexpected output on macOS. I fixed it for my situation by redirecting output to /dev/null: command cd "$(command dirname -- "$target")" >/dev/null 2>&1
–
Tsana GNU bash, version 3.2.57(1)
acts as /bin/sh
) - what unexpected output, specifically, are you getting? –
Suwannee ksh
but that turned out to be a problem with the ksh
implementation, not your script. Regardless, thank you for this script, it has been extremely valuable for building POSIX-compliant shell scripts that must be sourced and need to know their absolute location. –
Tsana @City responded that
DIR=$( cd -P -- "$(dirname -- "$(command -v -- "$0")")" && pwd -P )
works. I used it too.
I found the command at https://mcmap.net/q/13462/-can-i-get-the-absolute-path-to-the-current-script-in-kornshellrrent-script-in-kornshell.
sh
), whereas the question linked here is about ksh
, and the questions linked in comments at the top are bash
questions; while some of the answers to those questions happen to contain solutions that are also POSIX-compliant, they aren't discussed as such, and even though this question is closely related, it is distinct, of general interest, and deserves its own, canonical answer here. Perhaps Walter could have copied the ksh-tagged solution and explained why it works with all POSIX-compliant shells. –
Suwannee if [ -f "$0" ]; then script=$0; else script=$(command -v -- "$0"); fi
dir=$(dirname -- "$script")
dir=$(CDPATH=; cd -- "$dir" && pwd -P)
When a relative directory is all I need, as is usual, I omit the last line.
The snippet gives the right answer if the script is directly invoked (e.g., script
or path/to/script
), or if the shell is directly invoked with the script as first argument (sh script
or sh path/to/script
). You can use any POSIX-compliant shell instead of sh
.
The snippet does not give the right answer if the script is sourced (. script
or . path/to/script
). Some shells, such as bash and ksh93, have nonportable features that will let you get the answer, but it can't be done within POSIX.
The third line resolves directory symlinks; if you don't want to do that, remove the -P
after pwd
. The snippet does not resolve file symlinks. POSIX provides no simple way to do so.
The snippet must appear before the script cd
s for the first time.
The snippet's first line
if [ -f "$0" ]; then script=$0; else script=$(command -v -- "$0"); fi
computes a path to the script. In most cases that satisfy the conditions above, $0
is that path. [ -f "$0" ]
yields true, and $0
is assigned to the variable script
.
Now suppose your script is invoked via sh script
. That is, the shell is directly invoked and the script filename, without a slash character, is the first argument. There are two cases: either the script exists in the current working directory (first case) or it doesn't, but it's on the PATH (second case).
In the first case, $0
is the script filename, which is also a correct path. It's assigned to the variable script
, as above.
In the second case, POSIX allows the shell to search the PATH. (Some shells do, like bash and ksh93. Others don't, like dash and mksh. We assume we're in a shell that does.) $0
is again the script filename. But this time it isn't a path to the script, because the script doesn't exist in the cwd! [ -f "$0" ]
yields false; command -v
finds the script on the PATH; and the result is assigned to the variable script
.
The first case is why the first line cannot be reduced to script=$(command -v -- "$0")
; that would fail or produce the wrong result if the cwd were not in the PATH. The second case is why the first line cannot be reduced to script=$0
.
Let's move on to the second line:
dir=$(dirname -- "$script")
It extracts the directory part of $script
. Nothing to talk about there.
Finally, the third line
dir=$(CDPATH=; cd -- "$dir" && pwd -P)
ensures that the directory is absolute, and resolves directory symlinks.
The third line sets CDPATH to empty because otherwise, cd
can misbehave. And it does so in a separate statement (CDPATH=; cd
) rather than in the same statement (CDPATH= cd
) because the latter doesn't have the desired effect in /bin/sh
and /bin/ksh
on AIX, IBM's Unix.
if OLDPWD=/dev/fd/0 \
cd - && ls -lLidFH ?
then cd . <8
fi </proc/self/fd 8<. 9<$0
there. that should enable you to change directpry through some magic links as file descriptors.
setting $OLDPWD
pre-cd
exports the value for the duration of the one change directory (note: cd
can have residual effects on hash
tables, but the only sh
about which i am aware that actually males any good use of these is kevin ahlmquists - and since herbert xu - dash
, and maybe some bsd
stuff, but what do i know?) but does not carry over any cd
exports as a result of the change.
thus, $OLDPWD
does not change, actually, and if it had any value at all this remains as was. $PWD
is changed as a result of the first cd
, and the value becomes /dev/fd/0
which points to /proc/self/fd
, where a list of file descriptors for our process should be in .
, to include whatever $0
is on ./2
.
so we do an ls ... ?
and have a look at all of the wonderful info we can get, and we go whence we came.
yay!
/proc/self
). Unless you run the script sourced - in which you can't rely on $0
anyway - you needn't worry about OLDPWD
(which isn't a POSIX-mandated shell variable to begin with). When I run this on Ubuntu 18.04, I get literal /dev/fd/0
, followed by a listing of the process' file descriptors (plus an error message about descriptor 3
) - I don't see the script's (symlink-resolved) directory path, which is what the question is about. –
Suwannee cd -[LP]
for link memories sh local or properly canonical. the former method enables a ln -sf ~/../~\${../tmp/;cd <./0/.. -L [.-\9]
or `similar; for CDPATH in –
Lise cd -[LP]
for link memories sh local or properly canonical. the former method enables a ln -sf <~nobody/onthisfreakyphonedoesntchargeagainanduponwhichicannottestthisstuffforthreeyearswhilemysoniskidnappedbyunitedstatesnavy ~/../~"${HOME##*/}" /dev/fd/0;2<>~/../\~
... ehh... bored. cant even charge this last vestige of computing available... OLDPWD=/proc/$$/fd/$?/../root<~ cd -L ->>; cd -L ../$?<~somename
and so on.. theres another name space. try putting executables in an fd and linkinkg over them... you can mount like that. –
Lise find /proc/$$/fd -lname "*${0##*/}" -printf '%l\n'
gives the script itself, then dirname it. –
Suber © 2022 - 2024 — McMap. All rights reserved.
BASH_SOURCE
which is a bash-ism. There are other answers in this question and there's the mywiki.wooledge.org/BashFAQ/028 – AldoBASH_SOURCE
variable, which, obviously, is available only inbash
. – CockalorumDIR=$( cd -P -- "$(dirname -- "$(command -v -- "$0")")" && pwd -P )
, what I found athttp://stackoverflow.com/questions/760110/can-i-get-the-absolute-path-to-the-current-script-in-kornshell
. – Ratlinecommand
usage is supposed to be doing there. That seems like a mistake for anything not in thePATH
. – Aldocommand -v
will work as long as its argument is a path to an executable file (as opposed to a mere filename, in which case matches would be limited to the$PATH
). However, it merely echoes that path as is, and while it seems to do no harm, I have no idea why it's there. – Suwanneecommand
? I see the spec saying "command_names including a <slash> character ... shall be written as absolute pathnames" but that doesn't say anything about the executable part. – Aldocommand
(emphasis mine): "When the-v
or-V
option is used, the command utility shall provide information concerning how a command name is interpreted by the shell." – Suwanneesh
), notbash
, which is what the question you link to are tagged with; even though the answers there happen to contain solutions that are also POSIX-compliant, they aren't discussed as such. – Suwanneeksh
implements that way -dash
,bash
, andzsh
simply echo the path as specified. As an additional curiosity,dash
also echoes executable directories. I think I finally figured out the purpose ofcommand -v -- "$0"
- it's to - sort of - cover sourced invocation; see my updated answer. – Suwanneedash
actually echoes ANY existing path passed tocommand -v
- even directories - being executable is not a requirement - unlike inbash
,ksh
, andzsh
. – SuwanneeCURRENT_SCRIPT_DIRECTORY="$(basename "`pwd "$(dirname -- readlink $0)"`")"
– Kerr