如何在zsh脚本中获取文件名(而不是调用命令)?

时间:2015-10-04 20:31:53

标签: shell command-line zsh

我正在编写一个zsh脚本,它有几个符号链接。正常操作是通过其中一个链接调用脚本。

在某一点上,我想处理直接调用脚本的条件,而不是通过其中一个链接调用。为此,我需要使用用于调用脚本的命令并将其与脚本文件本身的名称进行比较。

似乎有几种方法可以获得调用命令($ 0和$ {(%): - %N}是两个例子)。但是,我不知道如何确定包含实际脚本源的FILE的名称。每一次发现的尝试似乎都引导我如何获得调用命令。

以下是一些示例代码,可能有助于说明我的意思:

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

在我在这里使用的具体例子中,我想如果第一个条件都不成立,我可以打印用法。这样可以处理这种情况,但如果我需要的话,我仍然会留下如何找到文件名的问题。

当然这是可能的。想法?

1 个答案:

答案 0 :(得分:1)

来自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