TCSH脚本完整路径

时间:2011-08-23 03:49:10

标签: shell tcsh

在bash shell中,即使脚本由source,link,。/ ...等调用,我也可以获得脚本的完整路径。 这些神奇的bash行:

 #Next lines just find the path of the file.
 #Works for all scenarios including:
 #when called via multiple soft links.
 #when script called by command "source" aka . (dot) operator.
 #when arg $0 is modified from caller.
 #"./script" "/full/path/to/script" "/some/path/../../another/path/script" "./some/folder/script"
 #SCRIPT_PATH is given in full path, no matter how it is called.
 #Just make sure you locate this at start of the script.
 SCRIPT_PATH="${BASH_SOURCE[0]}";
 if [ -h "${SCRIPT_PATH}" ]; then
   while [ -h "${SCRIPT_PATH}" ]; do SCRIPT_PATH=`readlink "${SCRIPT_PATH}"`; done
 fi
 pushd `dirname ${SCRIPT_PATH}` > /dev/null
 SCRIPT_PATH=`pwd`;
 popd  > /dev/null

如何在TCSH shell中获得相同条件下的脚本路径?这些“神奇的线条”是什么?

P.S。它不是this和类似问题的重复。我知道$0

2 个答案:

答案 0 :(得分:2)

如果您的csh脚本名为test.csh,那么这将起作用:

/usr/sbin/lsof +p $$ | \grep -oE /.\*test.csh

答案 1 :(得分:0)

我不使用tcsh并且不在其中声明guru状态,或C shell的任何其他变体。我也坚信Csh Programming Considered Harmful包含许多真理;我使用Korn shell或Bash。

但是,我可以查看手册页,我在MacOS 10.7.1 Lion上使用了tcsh(tcsh 6.17.00 (Astron) 2009-07-10 (x86_64-apple-darwin))的手册页。

据我所知,${BASH_SOURCE[0]}中的变量tcsh没有类似,因此缺少问题中脚本片段的起点。因此,除非我遗漏了手册中的内容,或者手册不完整,否则在tcsh中没有简单的方法可以获得相同的结果。

原始脚本片段也有一些问题,如评论中所述。如果使用名称/home/user1使用当前目录/usr/local/bin/xyz调用脚本,但这是一个包含../libexec/someprog/executable的符号链接,那么代码段将产生错误的答案(它可能会说/home/user1,因为目录/home/libexec/someprog不存在。)

此外,将while循环包裹在if中毫无意义;代码应该只包含while循环。

SCRIPT_PATH="${BASH_SOURCE[0]}";
while [ -h "${SCRIPT_PATH}" ]; do SCRIPT_PATH=`readlink "${SCRIPT_PATH}"`; done

你应该查看realpath()功能;甚至可能有一个使用它已经可用的命令。编写使用realpath()的命令当然不难。但是,据我所知,没有一个标准Linux命令包装realpath()函数,这很可惜,因为它可以帮助您解决问题。 (statreadlink命令没有帮助,具体而言。)

最简单的说,你可以编写一个使用realpath()的程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int main(int argc, char **argv)
{
    int rc = EXIT_SUCCESS;
    for (int i = 1; i < argc; i++)
    {
        char *rn = realpath(argv[i], 0);
        if (rn != 0)
        {
            printf("%s\n", rn);
            free(rn);
        }
        else
        {
            fprintf(stderr, "%s: failed to resolve the path for %s\n%d: %s\n",
                    argv[0], argv[i], errno, strerror(errno));
            rc = EXIT_FAILURE;
        }
    }
    return(rc);
}

如果该程序被调用realpath,则Bash脚本片段将缩减为:

SCRIPT_PATH=$(realpath ${BASH_SOURCE[0]})
相关问题