Execute code if a script directly called


I often want to run some arbitrary code if I run a script directly. The primary example that comes to mind these days is:

if __name__ == "__main__":
    print("This script was run directly")
else:
    print("This script was included")

Strangely enough, despite primarily using Ruby on a daily basis, I haven’t really thought about how this test looks in Ruby:

# ruby
if __FILE__ == $PROGRAM_NAME # $0 also works 
  # execute only if script directly called via `ruby script_name.rb`
end

Bash seemed a little more obvious, but apparently there’s a slightly more robust version of checking vs. just checking if static_filename.sh == $0:

# bash version
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
  # same for bash
fi

And I just looked up PowerShell, but haven’t validated it yet:

# powershell? (unverified)
if ($MyInvocation.MyCommand.Definition -eq $MyInvocation.MyCommand.Path) {
    Write-Host "Script was run directly"
} else {
    Write-Host "Script was called from $($MyInvocation.MyCommand.Definition)"
}

Leave a Reply