假设我在 /path/to/my_script.csh 中放置了一个可执行的 tcsh 文件
我的当前目录在任何地方,例如我在 /path
所以我输入到/my_script.csh
我想在 my_script.csh 中有一行返回 "/path/to/my_script.csh" - 就像 ruby 的
__FILE__
在 c shell 中,试试这样:
set rootdir = `dirname $0`
set abs_rootdir = `cd $rootdir && pwd`
echo $abs_rootdir
如果您想确保相同的结果(完整路径和脚本名称),请尝试以下操作:
...
rootdir=`/bin/dirname $0` # may be relative path
rootdir=`cd $rootdir && pwd` # ensure absolute path
zero=$rootdir/`/bin/basename $0`
echo $zero
...
然后,您可以将其称为 foo.sh、./foo.sh、some/lower/dir/foo.sh 并且无论如何调用它仍然会得到相同的结果。
如果你想要一个绝对路径,那么这应该可以帮助你:
#!/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"
来源:http ://tipsarea.com/2013/04/11/how-to-get-the-script-path-name-in-cshtcsh/
#!/bin/tcsh
echo "I am $0."