I am trying to obtain the absolute path to the currently running script on OS X.
I saw many replies going for readlink -f $0
. However since OS X's readlink
is the same as BSD's, it just doesn't work (it works with GNU's version).
Is there an out-of-the-box solution to this?
In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.
realpath(1) realpath uses realpath(3) to resolve the path of the filename(s) supplied as arguments and prints the result to stdout. realpath uses realpath(3) to resolve the path of the filename(s) supplied as arguments and prints the result to stdout.
The accepted answer to Getting the source directory of a Bash script from within addresses getting the path of the script via dirname $0 , which is fine, but that may return a relative path (like . ), which is a problem if you want to change directories in the script and have the path still point to the script's ...
To use full path you type sh /home/user/scripts/someScript . sh /path/to/file is different from /path/to/file . sh runs /bin/sh which is symlinked to /bin/dash . Just making something clear on the examples you see on the net, normally you see sh ./somescript which can also be typed as `sh /path/to/script/scriptitself'.
These three simple steps are going to solve this and many other OS X issues:
brew install coreutils
grealpath .
(3) may be changed to just realpath
, see (2) output
There's a realpath()
C function that'll do the job, but I'm not seeing anything available on the command-line. Here's a quick and dirty replacement:
#!/bin/bash
realpath() {
[[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}
realpath "$0"
This prints the path verbatim if it begins with a /
. If not it must be a relative path, so it prepends $PWD
to the front. The #./
part strips off ./
from the front of $1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With