11

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__
Julian Mann
  • 6,256
  • 5
  • 31
  • 43

4 Answers4

11

In c shell, try like this:

set rootdir = `dirname $0`
set abs_rootdir = `cd $rootdir && pwd`
echo $abs_rootdir
euccas
  • 755
  • 9
  • 13
  • Unfortunately when I do this in my #!/bin/csh script, and run it with a relative path (./myscript.csh), it always returns my home directory. Does not matter where I put this script. `dirname $0` is '.' and `pwd` returns my $HOME – mdiehl13 Mar 09 '16 at 21:39
  • @mdiehl13 The problem you described doesn't happen to me. Do you still see the same issue? You may need check your .cshrc file and see if there are any special configurations related to directory path setting. – euccas Mar 08 '18 at 06:52
  • @euccas No, strange (and good). I don't see this behavior anymore – mdiehl13 Mar 09 '18 at 17:06
6

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/

Lewis R
  • 433
  • 5
  • 9
  • 1
    Thanks for saving me any more frustration on how to differentiate between the source and a calling script – SunDontShine Jan 21 '20 at 18:54
  • This gives the correct result if sourced manually but not if sourced by another script. Is there a way, where it works in this case as well? – M0M0 Jul 04 '23 at 15:40
6

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.

DAS
  • 85
  • 1
  • 2
1
#!/bin/tcsh
echo "I am $0."
ndim
  • 35,870
  • 12
  • 47
  • 57