On 2017-10-30 03:09, Hongyi Zhao wrote:
> cd -P -- "$(dirname -- "$(realpath -e -- "$0")" )" &&
> werner@debian-01:~$ . .profile.d/obtain-script-dir.sh
> realpath: bash: No such file or directory
> /home/werner
> /home/werner
>
> As you can see, it cann't find the realpath command, and the output
> results are error.
No, I cannot see that. That is not what the error message means.
Rather, realpath runs, and cannot find a bash file in the current
directory.
I think you misunderstand what realpath does. It does not simulate the
search for an executable along the PATH directory list such as a shell
does when it interprets a command. realpath just canonicalizes the name
of an existing file, which means, converts a name to an absolute one and
resolves any symlinks in it (including names of enclosing directories
which are really symlinks to directories).
What I think you might be trying to do is a hard, and maybe impossible,
problem in Unix: getting the full absolute name of a script from within
the script itself, without help from any extra configuration. Rather
than trying your luck in this game where many have failed before,
consider the easy and robust solution with an external configuration
file in a fixed location. For example, if your script lives in
/home/werner/bin, put this into /home/werner/pathconfig.sh:
WERNER_SCRIPT_DIR=/home/werner/bin
and then in your script (assuming the script runs as user werner):
. ~/pathconfig.sh
# now do something/anything with $WERNER_SCRIPT_DIR ...
--
Please don't Cc: me privately on mailing lists and Usenet,
if you also post the followup to the list or newsgroup.
Do obvious transformation on domain to reply privately _only_ on Usenet.