Is there a way to set environment variable for x hours

Viewed 217

Trying to create an environment variable that will expire after a set amount of time.

Use case:
I login into a service on the terminal, I want to save e.g. ACC_ID=123456 to environment variables, then print that out in the terminal prompt:

(123456)-(name)$

Using the following fish method to set acc_id environment variable:

function acc_id
    cd /path/to/script/
    ./login_to_service.sh $argv
    set -Ux ACC_ID $argv
    cd -
end

ACC_ID persists until I re-run the acc_id function

After 1 hour I want this to do one of the following:

  • unset ACC_ID as an env variable
  • set ACC_ID to an empty string

I could setup a scheduled task do that, but I'm wondering if there's a more appropriate or built in way.

1 Answers

fish has an event-oriented system built into it. You can write a trigger that fires when an event occurs. One such event is when a process exits. So:

  • in your function, create a background process that sleeps for 1 hour
  • add a function that executes when that background process ends
  • that function will unset the env var:
function acc_id
    cd /path/to/script/
    ./login_to_service.sh $argv
    set -Ux ACC_ID $argv
    cd -
    # the magic
    sleep 1h &
    function _unset_accid --on-process-exit (jobs --last --pid)
        set -e ACC_ID
        functions -e (status function)
    end
end

I delete the function within the inner function: it will trigger anytime that pid number exits, so we don't want it hanging around waiting for any process with that pid.

Here's a demo:

$ function set_var_for_a_while
      set -gx MYENVVAR "variable value created "(date '+%s')
      sleep 5 &
      function _unset_my_var --on-process-exit (jobs --last --pid)
          set -e MYENVVAR
          functions -e (status function)
      end
  end

$ set_var_for_a_while; type _unset_my_var; for i in (seq 6); printf "%s\t%s\n" (date) $MYENVVAR; sleep 1; end; type _unset_my_var

Output:

_unset_my_var is a function with definition
function _unset_my_var --on-process-exit 68077
    set -e MYENVVAR
    functions -e (status function)
end
Mon Jun 24 10:21:51 EDT 2019    variable value created 1561386110
Mon Jun 24 10:21:52 EDT 2019    variable value created 1561386110
Mon Jun 24 10:21:53 EDT 2019    variable value created 1561386110
Mon Jun 24 10:21:54 EDT 2019    variable value created 1561386110
Mon Jun 24 10:21:55 EDT 2019    variable value created 1561386110
Mon Jun 24 10:21:56 EDT 2019
type: Could not find '_unset_my_var'
Related