Created
November 16, 2025 19:29
-
-
Save alexanderadam/6a9f669060d6420f550a8eb70d69fece to your computer and use it in GitHub Desktop.
Per project shell history
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Per-project history | |
| function _set_project_history() { | |
| local project_id="" | |
| # Check if we're in a git repository | |
| if git rev-parse --git-dir > /dev/null 2>&1; then | |
| # Try to get the remote URL (origin by default) | |
| local remote_url=$(git config --get remote.origin.url 2>/dev/null) | |
| if [ -n "$remote_url" ]; then | |
| # Sanitize the remote URL to create a valid filename | |
| # Removes protocol, converts slashes and special chars to underscores | |
| project_id=$(echo "$remote_url" | sed -e 's|^.*://||' -e 's|^.*@||' -e 's|:|_|g' -e 's|/|_|g' -e 's|\.git$||') | |
| else | |
| # Fallback: use the repository's .git folder's inode or unique ID | |
| # This works for local repos without remotes | |
| local git_dir=$(git rev-parse --absolute-git-dir 2>/dev/null) | |
| if [ -n "$git_dir" ]; then | |
| # Use a hash of the git directory path for uniqueness | |
| project_id=$(echo "$git_dir" | md5sum | cut -d' ' -f1) | |
| fi | |
| fi | |
| fi | |
| # Set history file based on project ID | |
| if [ -n "$project_id" ]; then | |
| mkdir -p "$HOME/.shell_histories" | |
| export HISTFILE="$HOME/.shell_histories/${project_id}_history" | |
| else | |
| # Use default global history when not in a git repo | |
| if [ -n "$ZSH_VERSION" ]; then | |
| export HISTFILE="$HOME/.zsh_history" | |
| else | |
| export HISTFILE="$HOME/.bash_history" | |
| fi | |
| fi | |
| } | |
| # Hook into directory changes | |
| if [ -n "$ZSH_VERSION" ]; then | |
| # Zsh hook | |
| autoload -U add-zsh-hook | |
| add-zsh-hook chpwd _set_project_history | |
| else | |
| # Bash hook | |
| PROMPT_COMMAND="_set_project_history; $PROMPT_COMMAND" | |
| fi | |
| # Set history on shell startup | |
| _set_project_history |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment