3 ms·
The portablest solution I have found is: rundir=$(cd -P -- "$(dirname -- "$0")" && printf '%s\n' "$(pwd -P)")
by mhio 3y ago
The portablest solution I have found is:
rundir=$(cd -P -- "$(dirname -- "$0")" && printf '%s\n' "$(pwd -P)")
- HerrMonnezza 3y agoI'm curious: why the `printf '%s\n' "$(pwd -P)"` ? wouldn't just `pwd -P` achieve the same?
- alganet 3y agoI've been using just `V="$(cd -- "$(dirname -- "$0")"; pwd)"` for ages, everything quoted, several OSs, never had an issue with the output that required me to format it again. This approach breaks if you run the script from a symlink.
- mhio 3y agoActually nothing. The format seems to have come from a similar line that builds the script path.. printf '%s/%s\n' "$(pwd -P)" "$(basename "$0")" It's just been in place, in so many places, so long it's become unquestionable. So yes the `pwd -P` in this case will suffice.
- account42 3y agoThis isn't a portable solution at all because it doesn't solve the problem of the script being symlinked. While it does resolve directory symlilnks, that part is usually not even needed as finding a helper works just as well with a symlink to the directory containing the script as it does with the resolved directory. What doesn't work is a directory containing a symlink to the script which your "solution" fails to resolve. Additionally (and the article doesn't solve this either), when invoked through $PATH, $0 will not be a full path but only the name of the command. In that case you want to start with "$(command -v "$0")" instead of just "$0".
- Asooka 3y agoNo, $0 is a full path when invoked via $PATH.