Skip Navigation

How to make it such that, when running command, it automatically does SOME_ENV_VAR=value command? (something cleaner than aliases?)

hello friends,

I am looking for a way to do what I described in the title. When running command command, I dont want to have to type SOME_ENV_VAR=value command every time, especially if there are multiple.

I am sure youre immediately thinking aliases. My issue with aliases is that if I do this for several programs, my .bashrc will get large and messy quickly. I would prefer a way to separate those by program or application, rather than put them all in one file.

Is there a clean way to do this?

21 comments
  •  undefined
        
    function command_one() {
        # activate the environment
        source "$XDG_DATA_HOME/venvs/alpha.sh"
        # run the thing
        actual_command_one
    }
    
    function command_two() {
        # activate the environment
        source "$XDG_DATA_HOME/venvs/alpha.sh"
        source "$XDG_DATA_HOME/venvs/bravo.sh"
        # run the other thing
        actual_command_two
    }
    
    
      
  • You could alias the your programs' commands to invoke the environment variables.

    Or, use an alias to source an environment file before launching the binary?

  • If you were using Zsh, one way you could do this is by autoloading function files from a folder in your fpath.

    Let's say you're using ~/.local/share/zsh/site-functions for your custom functions. To ensure that folder is an early part of your fpath, put something like this within your .zshrc:

     undefined
        
    typeset -U fpath=(~/.local/share/zsh/site-functions $fpath)
    
      

    Then let's say you want to override the uptime command. Add a file ~/.local/share/zsh/site-functions/uptime with content like:

     undefined
        
    NO_COLOR=1 =uptime
    
      

    The last thing you need to do is mark it for autoloading, in your .zshrc:

     undefined
        
    autoload -Uz uptime
    
      

    Instead of listing those functions manually as arguments, you could instead use a glob pattern to collect all those names, excluding any which begin with _ (completion functions):

     undefined
        
    autoload -Uz ~/.local/share/zsh/site-functions/[^_]*(:t)
    
    
      
21 comments