Theis
Theis

Reputation: 53

Local git functions

I figured out how to make functions for git bash to load in windows using the .bashrc file in my home folder (with the workaround of .bash_profile):

# Example
function cush() {
    git add Figures/;
    git commit -am "$1";   # Parse string to git
    git push;
}

But this function is dedicated to LaTeX and I actually only need to use it when working in specific types of repositories. So my question is whether there is a way to make functions locally, such that it will load upon loading git bash in that specific folder? This motivates functionality that is specific for the repository, just like .gitignore is.

Upvotes: 0

Views: 398

Answers (2)

chepner
chepner

Reputation: 532313

Typically, you don't worry about having unnecessary functions defined unless you want to use the same name for different, context-dependent functions. bash doesn't directly provide a hook for executing code when the working directory changes, but you can (ab)use PROMPT_COMMAND to conditionally execute code based on the value of $PWD each time a new prompt is displayed.

  1. Create a directory named .bash-functions
  2. Put your LaTex-specific functions in .bash-functions/latex
  3. Create a file .bash-functions/un-latex which contains code to unset your LaTeX-specific functions, something like

    unset -f cush
    
  4. Add the following to your .bashrc:

    source_local_functions () {
        source ./bash-functions/un-latex
        if [[ $PWD == foo ]]; then
            source ./bash-functions/latex
        fi
    }
    PROMPT_COMMAND=source_local_functions
    

Now, each time you display a new prompt, bash will unset your LaTex-specific functions, then reset them if you are in a directory named foo (you can obviously adjust this test for the real directories which should use the LaTeX functions).

This gets unwieldy if you have other directory-specific functions to define, as you need to keep track of which functions to unset and which ones to set for every change of directory.

Upvotes: 1

ElpieKay
ElpieKay

Reputation: 30956

This question may help. I tried this solution and it could work in my Ubuntu15.x and git version 2.8.2 while the others have errors.

[alias] cush = !git add . && git commit -m $1 && git push && :

so you can add this alias into the local config and run git cush <message>.

Upvotes: 1

Related Questions