2

I regularly invoke a particular remote server from a (Linux/bash) command line via tools like cURL or wget. This server requires an authentication token that expires every 10 minutes. I have a program that can generate a new token.

What I would like is an environment variable, $TOKEN, that I can use from the command line, that refreshes itself every 10 minutes, or, better yet, refreshes itself only when requested, and even then only every 10 minutes at most.

I was hoping that there was a way to tie an environment variable's evaluation to an executable, allowing me to do so with a script. Failing that, I was wondering if perhaps there was a way to set up a background process that updated the environment variable every 10 minutes.

3 Answers3

0

You could set up a cron job that calls a script every 10 minutes (or whatever time interval you want). Then the script updates the variable.

See: linux: how to permanently and globally change environment variables

smcg
  • 505
  • 4
  • 18
0

you could create an alias to update the env var

alias token='TOKEN=$(wget -q -O - http://webserver.com/TOKEN)'

or

alias token='TOKEN=$(/path/to/token-generator)'

then, simply running "token" will set that var for current session

you can add to your bash profile, so the alias remains accross logins

nandoP
  • 2,021
  • 14
  • 15
  • Well, yeah, but then I need to remember to run "token" every so often. That's what I'm trying to avoid. – Brandon Yarbrough Sep 25 '13 at 17:48
  • 2
    if you write a script that returns the token and checks for invalid/old ones, then prints it to stdout, you can invoke it as $(scriptname). If you wish to optimize out the script call, you may be able to build a bash function that has the same effect but checks the age of the cookie first (in a different variable). That variable wouldn't be shared across different scripts though, unless it was reading from a shared file of some sort. – Andrew Domaszek Sep 25 '13 at 18:15
  • Ahhhhh, I had forgotten about the $(executable) trick. That's perfect, thanks! – Brandon Yarbrough Sep 25 '13 at 19:14
0

Store two environment variables, TOKEN and TOKEN_TIMESTAMP.

if [ $(($(date +%s) - $TOKEN_TIMESTAMP)) -ge 600 ]; then
  /script/to/update/token.sh
  TOKEN_TIMESTAMP=$(date +%s) # this should be in the above script.
fi

/script/that/uses/token.sh # everything could be in this one script.

This way you don't have to store logic in an environment variable [ew] or set up a cron job. The token is refreshed on-demand.

Sammitch
  • 2,111
  • 1
  • 21
  • 35