Search code examples
windowsgitwindows-subsystem-for-linuxgithooks

Set environment variable on branch checkout/switch


I'm using the post-checkout hook to try and set environment variables when switching branches.

#!/bin/sh

echo "Updating environment variables..."

OLD_IFS=$IFS
IFS=$'\n'

for x in $(cat .env | sed -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/='\1'/g")
do
    var_name=$( cut -d '=' -f 1 <<< "$x" )
    export $x
    pwsh.exe -c "\$env:$x"
    pwsh.exe -c "echo 1; echo \$env:$var_name"
    export $x
done

IFS=$OLD_IFS

The problem is that git hook is executed with WSL so the variables I set are lost after the post-hook

I assume this is because of the shebang?

I've tried #!/usr/bin/env pwsh but I get the error Processing -File '.git/hooks/post-checkout' failed because the file does not have a '.ps1' extension. Specify a valid PowerShell script file name, and then try again.

Is this something that can be done? I want to automatically change the DB connection when I switch branches.


Solution

  • As anthony sottlie noted, you can't do it that way.

    What you need instead is a command that you run instead of git switch or git checkout. In this command, you will:

    1. run git switch or git checkout, then
    2. set the environment variables you would have set in your script, the way you would have set them

    and since this will be done by the command itself, rather than in a subprocess, it will affect further commands run by this same command-line interpreter.