2015-10-04 34 views
-1

我正在写一个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

从人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 
+0

感谢这个!这让我疯狂。我认为bash可能具有相同的功能,但这仍然让我感到zsh再一次令人印象深刻。 P.S.,无论谁:我认为downvote是,嗯..问一个问题,哪个答案已经记录?那么,如果这些都是规则,好吧,但是'扩张'并不是我在尝试(和我确实)找到答案时想到的第一件事情。现在我明白了。活到老,学到老。 –

相关问题