假设我将可执行的 tcsh 文件放在 /path/to/my_script.csh 中
而我的当前目录是任意的,例如我在 /path 中
那么我输入 to/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
#!/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/
如何获取CSH / TCSH脚本的路径名?...
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
echo "I am $0."
dirname $0
是'.',而pwd
返回我的$HOME。 - mdiehl13