1

I have a fish script that exports some variables and launches a command at the end. I'd like to be able to source this file to bring these variables into the current shell session, but without executing the command at the end.

The question: Can I figure out whether the current file is being executed or sourced from within the file?

Giacomo1968
  • 55,001
mkaito
  • 2,062

3 Answers3

2

You can use the $_ environment variable to see if your script is being "run" by the source command. Note that the source command has a common alias ("."), so you must check the $_ environment variable against both source and ..

#!/bin/fish

if test "$" != "source" -a "$" != "." echo "not sourced" else echo "was sourced" end

A common use of this may be to give a warning to the user, iff the script was not sourced:

if test "$_" != "source" -a "$_" != "."
    echo "Run this script with \". ./activate.fish\" (aka: \"source ./activate.fish\")."
    exit 1
end

Replace activate.fish with the name of your script, of course.

2

You can use the $_ environment variable to see if your script is being "run" by the source command:

#!/bin/fish
if test "$_" = source
  echo got sourced
else
  echo was execed
end
meuh
  • 6,309
1

I think you misunderstand what "source"ing a script does. Generally, executing a script will run it in a separate process. Sourcing it will execute it in the current shell. It will still execute each line.

Probably what you want to do is to filter out the last line. Try:

source (sed '$d' filename | psub)

The psub command is used to handle the output of some process as if it is a file. Documentation

glenn jackman
  • 26,306
  • That works, and is pretty interesting. What I was thinking about was something akin to the if __name__ == __main__ trick from python, but this works just as well. – mkaito Jul 22 '15 at 01:50