Reputation: 840
How can I determine if the current tcsh
script is being sourced (within the script)?
What I tried:
if (!($0 == "-tcsh")) then
echo "Script should be sourced."
exit 1
endif
If I'll try without source it will print Script should be sourced.
(As expected).
But If I'll try with source, it will fail with the following error: if: Malformed file inquiry.
.
How can I fix this problem? Is there a better way to check it?
Upvotes: 0
Views: 1006
Reputation: 1
kvantour's anwser is wrong. In tcsh the value of $_
will not be set correctly unless the script is sourced from a command line/terminal. There is a guy at Intel that works on their icc compiler that must think the same way, which is where my issue is.
Simple example to prove the point:
script.csh
:#!/bin/csh
echo "Got: " $_
In a terminal:
Run source script.csh
; you will get the output of "Got: source script.csh"
Run script.csh
; you will get the output of "Got: "
Run ssh $HOST 'source script.csh'
; you will get the output of "Got: "
So even though you sourced the script the $_
value is not set. This happens when you have a headless terminal. So if I put source scripts.csh
inside of my .cshrc
, $_
will not be set, which causes issues. So do not implement the solution here.
If I find the right answer I will update this post.
Upvotes: 0
Reputation: 86
While there might be other ways to do that, a simple enhancement to your own method works fine. Just enclose the $0 within double quotes. i.e change the line
if (!($0 == "-tcsh")) then
to
if (!("$0" == "-tcsh")) then
Upvotes: 0
Reputation: 26471
There is a nasty trick you can play here by looking at $_
.
$_
Substitutes the command line of the last command executed.
If you place this in the first line of your script, and the outcome is not an empty string (i.e. a command has been executed before), then the script has been sourced.
#!/usr/bin/env tcsh
set sourced = ($_)
if ("$sourced" == "") then
echo "Script should be sourced."
exit 1
endif
Information picked from https://unix.stackexchange.com/questions/4650/determining-path-to-sourced-shell-script
Upvotes: 2