4

I am sourcing a file under tcsh. This file could be anywhere on the filesystem. How can I retrieve the path of my sourced file ?

$0 won't work : I don't execute the file, I source it.

Many thanks !

Charles
  • 263
  • 1
  • 3
  • 10

5 Answers5

4

If you do not want to use lsof, use below for csh only.

set script_path = `ls -l /proc/$$/fd | sed -e 's/^[^/]*//' | grep "/script_name"`

$$ is the pid of the current running thread.

No matter which method (sourced by user or in other script), the script be called, is also be opened. So filter the content of fd will get the real path of script.

This also works when the script is soft linked to other path!

TerrenceSun
  • 141
  • 5
2

A little bit of grepping gives me what I want.

There is one thing I know for sure : the basename of the file (not the whole path). In my case, source_me.tcsh. So we can query lsof for the current shell PID and grep the absolute path.

$$ gives you the PID.

/usr/sbin/lsof +p $$ | grep -oE /.\*source_me.tcsh
Charles
  • 263
  • 1
  • 3
  • 10
  • Both this approach, and the sed approach by @TerranceSun, breaks when the source script is used in a pipe: `source script.csh | grep foo` – jdi Jul 10 '18 at 23:28
1

You can try following, which should work in normal (t)csh. I do not know if it also works in the .(t)cshrc:

#!/bin/csh
set DUS = ( $_ ) #DUS: Dollar UnderScore
set DNU = $0:q   #DNU: Dollar NUll
if (( $#DUS > 1 )) then
  if ("${DUS[1]}" == 'source' || "$DNU:t" == 'tcsh' || "$DNU:t" == 'csh') then
    set DNU = ${DUS[2]:q}
  endif
endif
echo 'Your script path is: '`(cd "$DNU:h" >&! /dev/null; pwd)`
echo 'your script name is: '$DNU:t
mili
  • 11
  • 1
  • This does not work if the `source` command is located inside another sourced script; this code will then print the name of the "outer" script, not of the actual inner script. – oliver Jul 31 '17 at 11:34
  • Also if you chain commands with `;` like `echo hello; source myscript` it will find the `hello` part rather than the script. – oliver Jul 31 '17 at 11:54
0

As far as I know sourcing means that you run it as if you were typing the commands one by one in the command line. Then, of course, you can't access its name, because he's not being executed as a script in the first place.

But you might be lucky: try to look in the command log. In bash you just type "history", dunno about tcsh but I guess there must be one there too.

o0'.
  • 411
  • 5
  • 20
0

While this is possible in other shells, I don't see a way to do it in tcsh.

Dennis Williamson
  • 60,515
  • 14
  • 113
  • 148