Can I use a shebang to have a file source itself into current bash environment?

No. By the time a shebang comes into play, you have already lost. A shebang is applied when a process is exec()'d and typically that happens after forking, so you're already in a separate process. It's not the shell that reads the shebang, it's the kernel.


As user @muru says, it's not possible to do because you have already left the shell session behind when you get to the #!-line.

However, depending on what your shell files do, there might be another solution.

I'm guessing that they set environment variables that you use for some project.

Let's call a project subtool (because that's a project I have). Then you could have a script that sets up a shell environment for projects, project-env for example:

#!/bin/bash

PROJECT="$1"
PROJECT_ROOT="$HOME/projects/$PROJECT"

cd "$PROJECT_ROOT" || exit 1
source "$PROJECT.env"

export PS1="[$PROJECT: \W] \$ "
exec bash -i

Run with:

$ ./project-env subtool

This will automatically cd into the given project subfolder beneath $HOME/projects, read a project environment file called subtool.env in this case (in which you initialize variables), give you a command line prompt for the project and leave you at an interactive bash session:

[subtool: subtool] $

When your work is done, simply exit.

This also has the benefit of isolating the project environment from your "ordinary" login shell session and from other projects.


The she-bang is interpreted by the kernel when a command is executed, not the shell. So, by that time, it's too late.

You can make it instead:

#! /bin/echo Please run (from a Bourne-like shell): .

Or:

#! /bin/sed 2,5!d;s/^#.//
# This script must be sourced from within a shell
# and not executed. For instance with:
# 
#   . path/to/that/script
rest of the script

To tell the user what they did wrong.

Which should work on Linux. Replace all but the first space with one of the non-ASCII spacing characters (like U+00A0, U+2006...) on some other OSes. You may have to adapt the path of the echo or sed utilities.