How to tell if file is being executed directly

Let’s say I have a file, foo.exs with the following contents:

defmodule Foo do
  def bar do


What I would like to do is not run the IO.puts statement if the file is not being run directly via elixir. Is there any way to do this? I see there is __ENV__.file, but not sure how I can use that to accomplish it.

How it is done in some other languages, for example:

I also understand that using Mix and having a greater separation of concerns can solve this particular problem, but I’m curious if its possible to do without using Mix at all.


I would rather refactor my code so that the modules that work both in a project and when run directly would be moved into .ex files, and then the code to be run directly would be in a .exs and use those modules.

Let’s say you have a foo.ex:

defmodule Foo do
  def bar(), do: IO.puts("Bar!")

and a test.exs just containing Now you can run elixir -pr "*.ex" test.exs and it will print Bar!.

Another option which I suggest looking into (without knowing what you are actually trying to do) are Mix tasks (I know you wanted to avoid Mix but look into it). That allows you to have tasks in your project that can be run on the command line and that can use the modules of your project. Then you can run them with mix your.task.

If you elaborate on your exact use case, then maybe we can suggest other methods.