Here a C shell snippet get_script_path.csh to do the trick.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#!/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
1 2 3 4 5 6 |
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).
1 2 3 4 5 6 |
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
Pingback:How To Add Syntax Highlight for Code in WordPress | Tips Area
thanks a lot
Works with tcsh. Fails with csh.
In fact we have more than two ways to run the script. What if we call the script from another script then $0 will be related with the script calling the executed script and will give the path of the script being executed (not the one that has been called which is the one that we want).