Reputation: 6476
Say I put an executable tcsh file in /path/to/my_script.csh
and my current directory is anywhere, for example I'm in /path
So I type to/my_script.csh
I want to have a line in my_script.csh that will return "/path/to/my_script.csh" - like ruby's
__FILE__
Upvotes: 11
Views: 27901
Reputation: 470
The following method works both when sourced from terminal and from another script:
(Assuming the filename to be sourced is "script.cshrc")
set sourced=`ls -l /proc/$$/fd | sed -e 's/^[^/]*//' | grep "/script.cshrc"`
set source_dir="`dirname $sourced`"
set script_dir=`realpath $source_dir`
The first statement lists open file descriptors of the current process (which includes the sourced script) and grep for its full path.
Upvotes: 1
Reputation: 468
If you want an absolute path then this should help you out:
#!/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"
Source: http://tipsarea.com/2013/04/11/how-to-get-the-script-path-name-in-cshtcsh/
Upvotes: 8
Reputation: 775
In c shell, try like this:
set rootdir = `dirname $0`
set abs_rootdir = `cd $rootdir && pwd`
echo $abs_rootdir
Upvotes: 11
Reputation: 85
If you want to ensure the same result (full path and script name) try something like this:
...
rootdir=`/bin/dirname $0` # may be relative path
rootdir=`cd $rootdir && pwd` # ensure absolute path
zero=$rootdir/`/bin/basename $0`
echo $zero
...
Then you can call it as foo.sh, ./foo.sh, some/lower/dir/foo.sh and still get the same result no matter how it is called.
Upvotes: 6