Skip to content

Instantly share code, notes, and snippets.

@Sekiphp
Created February 25, 2023 12:12
Show Gist options
  • Save Sekiphp/3866d027f66e76f4b184d3f52971ede7 to your computer and use it in GitHub Desktop.
Save Sekiphp/3866d027f66e76f4b184d3f52971ede7 to your computer and use it in GitHub Desktop.
Working on Ubuntu 20.04 LTS
#!/bin/bash
echo "SSH agent init script"
env=~/.ssh/agent.env
agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }
agent_start () {
echo "Starting new SSH agent"
(umask 077; ssh-agent >| "$env")
. "$env" >| /dev/null ;
}
agent_load_env
# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)
# echo "Agent run state: ${agent_run_state}"
# echo "Auth sock: ${SSH_AUTH_SOCK}"
if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
agent_start
find ~/.ssh/ -type f -exec grep -q "PRIVATE KEY" {} \; -print | xargs -d '\n' ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
ssh-add
fi
export SSH_AUTH_SOCK
unset env
echo "SSH agent was loaded"
@Sekiphp
Copy link
Author

Sekiphp commented Feb 25, 2023

This SSH agent configuration working with multiple tabs in microsoft/terminal app. Important part is export SSH_AUTH_SOCK to share variables between tabs.

If you are calling like separate script in ~/.bashrc do not forget to call it like: source ./scripts/ssh_agent.sh.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment