Here a C shell snippet get_script_path.csh to do the trick.

#!/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"

We have two ways to run the script, to illustrate why we need to handle differently, we print out the internal strings.

1. Source the script file

tps-VirtualBox:~/test> source ./get_script_dir.csh
branch 1
A:tcsh
B:source ./get_script_dir.csh 
script file name=/home/tps/test/get_script_dir.csh
script dir=/home/tps/test

2. Directly run the script (need to chmod to allow execution).

tps-VirtualBox:~/test>  ./get_script_dir.csh
branch 2
A:./get_script_dir.csh
B:
script file name=/home/tps/test/get_script_dir.csh
script dir=/home/tps/test

After you understand what the script is doing. You can delete all the extra echo command in the script.




How To Get The Script Path Name in CSH/TCSH
Tagged on:         

2 thoughts on “How To Get The Script Path Name in CSH/TCSH

Please tell us what's in your mind ...

%d bloggers like this: