說我把一個可執行文件的tcsh在/path/to/my_script.csh我如何找到正在執行的tcsh shell腳本的位置?
和我的當前目錄是在任何地方,比如我在/路徑
所以我鍵入/ my_script.csh
我想在my_script.csh一行將返回「/path/to/my_script.csh」 - 像Ruby的
__FILE__
說我把一個可執行文件的tcsh在/path/to/my_script.csh我如何找到正在執行的tcsh shell腳本的位置?
和我的當前目錄是在任何地方,比如我在/路徑
所以我鍵入/ my_script.csh
我想在my_script.csh一行將返回「/path/to/my_script.csh」 - 像Ruby的
__FILE__
如果你想確保SAM Ë結果(完整路徑和腳本名)嘗試這樣的事:
...
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,一些/下/ DIR/foo.sh仍能獲得無論怎樣調用,結果都是一樣的。
#!/bin/tcsh
echo "I am $0."
在C shell中,嘗試這樣的:
set rootdir = `dirname $0`
set abs_rootdir = `cd $rootdir && pwd`
echo $abs_rootdir
感謝您爲我節省翻譯。提問者似乎想要csh,並接受sh語法,這很奇怪。 – stevesliva 2015-02-11 18:56:30
不幸的是,當我在#!/ bin/csh腳本中執行此操作並使用相對路徑(./myscript.csh)運行它時,它始終返回我的主目錄。無論我在哪裏放這個腳本。 'dirname $ 0'是'。'和'pwd'返回我的$ HOME – mdiehl13 2016-03-09 21:39:36
@ mdiehl13您描述的問題不會發生在我身上。你仍然看到同樣的問題?您可能需要檢查.cshrc文件,看看是否有任何與目錄路徑設置相關的特殊配置。 – euccas 2018-03-08 06:52:05
如果你想要一個絕對路徑,那麼這應該幫助你:
#!/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 excution 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/
謝謝!工作得很好。 – 2012-01-05 04:02:20