Conditional getenv and cachebusting

I was about to ask this question and as I was writing it out, I thought I should have one last look in hugo docs, and lo and behold, I got a solution.

Basically, for cachebusting I wanted to append git commit hash of css file

<link rel="stylesheet" href="style.css?v=66379f8">

In my deploy script written in bash, I have exported said hash.
git has a very handy way of getting last commit hash of individual file or directory.

export CSS_HASH="$(git log -1 --format='%h' path/to/css/)"

In hugo 1.4, there is a new function getenv. According to docs, it returns empty string if variable not set, else it returns said environment variable.
So, while doing development, if CSS_HASH is not exported, the css url will have ?v= empty param. If you are like me and it bugs you, this can be fixed by -

<link rel="stylesheet" href="style.css{{with getenv "CSS_HASH"}}?v={{.}}{{end}}"

This will give nice url both in development and production. :slight_smile:

On the sidenote, If anyone can tell about doing if...else with getenv variables.

1 Like

Not sure what you mean by if/else, but with supports an else.

@bep Thanks, didn’t knew that, will keep in mind.

Thanks for this. My deploy script is a zsh function.

I needed export in front of the variable name to get this to work:

    export CSS_HASH="$(git log -1 --format='%h' /path/to/my/style.css)"

Without export, the var gets set, but, the other commands in the function don’t see it, apparently.

Just checked my bash script. I too have export in front of variable.
Don’t know how I missed it at time of writing the post. :stuck_out_tongue:

1 Like

good to know @2vek