Reputation: 3436
I'm writing a zsh script that has a couple of symbolic links to it. Normal operation is to invoke the script via one of the links.
At a certain point, I want to handle the condition where the script was called directly, instead of being called via one of the links to it. To do that, I need to take the command used to invoke the script and compare it to the name of the script file itself.
There seem to be several ways to get the invoking command ($0 and ${(%):-%N} are two examples). I do not know, however, how to determine the name of the FILE containing the actual script source. Every attempt to find out just seems to lead me to how to get the invoking command.
Here's some example code that may help to illustrate what I mean:
invoking_command=$(basename $0)
# If we're called via one symbolic link, do one thing.
if [[ $invoking_command = "link-one" ]]; then
condition="link-one"
fi
# If we're called via the other link, do something else.
if [[ $invoking_command = "sapti" ]]; then
condition="link-two"
fi
# If we're called directly, do something like, for example,
# recommend to the user what the expected usage is.
if [[ $invoking_command = (??? WHAT GOES HERE ???) ]]
condition="script file was run directly"
usage && exit
fi
In the specific example I use here, I suppose I could just print usage if neither of the first conditions are true. That would handle this case, but I'm still left with the question of how to find the file name if I ever need to.
Surely this is possible. Ideas?
Upvotes: 0
Views: 431
Reputation: 1077
from man zshexpn:
a Turn a file name into an absolute path: prepends the current directory, if necessary, and resolves any use of `..' and `.' in the path. Note that the transformation takes place even if the file or any intervening directories do not exist. A As `a', but also resolve use of symbolic links where possible. Note that resolution of `..' occurs before resolution of sym- bolic links. This call is equivalent to a unless your system has the realpath system call (modern systems do).
#!/usr/local/bin/zsh
mypath=$0:A
invoker=$0
echo $mypath
echo $invoker
Upvotes: 1