Path 如何找到tcsh shell脚本I';我在执行?

Path 如何找到tcsh shell脚本I';我在执行?,path,shell,directory,tcsh,Path,Shell,Directory,Tcsh,假设我在/path/to/my_script.csh中放置了一个可执行的tcsh文件 我的当前目录在任何地方,例如我在/path中 因此,我键入/my_script.csh 我想在my_script.csh中有一行返回“/path/to/my_script.csh”——就像ruby的一样 __FILE__ 如果要确保相同的结果(完整路径和脚本名称),请尝试以下操作: ... rootdir=`/bin/dirname $0` # may be relative path rootd

假设我在/path/to/my_script.csh中放置了一个可执行的tcsh文件

我的当前目录在任何地方,例如我在/path中

因此,我键入/my_script.csh

我想在my_script.csh中有一行返回“/path/to/my_script.csh”——就像ruby的一样

__FILE__

如果要确保相同的结果(完整路径和脚本名称),请尝试以下操作:

...
rootdir=`/bin/dirname $0`       # may be relative path
rootdir=`cd $rootdir && pwd`    # ensure absolute path
zero=$rootdir/`/bin/basename $0`
echo $zero
...
set rootdir = `dirname $0`
set abs_rootdir = `cd $rootdir && pwd`
echo $abs_rootdir

然后,您可以将其命名为foo.sh、./foo.sh、some/lower/dir/foo.sh,并且无论如何调用,都会得到相同的结果。

在c shell中,请尝试以下操作:

...
rootdir=`/bin/dirname $0`       # may be relative path
rootdir=`cd $rootdir && pwd`    # ensure absolute path
zero=$rootdir/`/bin/basename $0`
echo $zero
...
set rootdir = `dirname $0`
set abs_rootdir = `cd $rootdir && pwd`
echo $abs_rootdir

如果您想要一个绝对路径,那么这将帮助您:

#!/bin/tcsh -f 
set called=($_)

if ( "$called" != "" ) then  ### called by source 
   echo "branch 1"
   set script_fn=`readlink -f $called[2]`
else                         ### called by direct execution of the script
   echo "branch 2"
   set script_fn=`readlink -f $0`
endif

echo "A:$0"
echo "B:$called"
set script_dir=`dirname $script_fn`

echo "script file name=$script_fn"
echo "script dir=$script_dir"

来源:

不幸的是,当我在我的#中这样做时/bin/csh脚本,并使用相对路径(./myscript.csh)运行它,它总是返回我的主目录。不管我把这个脚本放在哪里
dirname$0
is'.'和
pwd
返回my$HOME@mdiehl13你描述的问题没有发生在我身上。你还看到同样的问题吗?您可能需要检查.cshrc文件,看看是否有任何与目录路径设置相关的特殊配置。@euccas否,奇怪(良好)。我再也看不到这种行为了错误的shell-\这给出了从当前目录到脚本的路径,而不是绝对路径。感谢您在如何区分源脚本和调用脚本方面为我省去了更多的麻烦