6.3.3.2. Automatic agent loading (subshell method)
The second way to load an agent on login uses the subshell method to
invoke the agent. This time, you need to add lines to both your login
initialization file (
~/.profile or
~/.login), an optional second file of your
choice, and your shell initialization file
(
~/.cshrc,
~/.bashrc,
etc.). This method doesn't work for the Bourne shell, which has
no shell initialization file.
- In your login initialization file, make sure
you're not already running an agent, by testing environment
variable SSH_AUTH_SOCK or SSH2_AUTH_SOCK.
- As the last line of your login initialization file, exec
ssh-agent, which spawns a subshell. Optionally run
a second initialization file to configure
aspects of the subshell.
- In your shell initialization file, check whether
the shell is attached to a tty and that the agent has no identities
loaded yet. If so, load your default identity with
ssh-add1 or ssh-add2.
Now let's see how to do this with Bourne shell and C shell
families. For derivatives of Bourne shell (
ksh,
bash), put the following lines at the end of
~/.profile :
test -n "$SSH_AUTH_SOCK" && exec ssh-agent $SHELL
This runs the agent, spawning a subshell. If you want to tailor the
environment of the subshell, create a script (say,
~/.profile2) to do so, and use this instead:
test -n "$SSH_AUTH_SOCK" && exec ssh-agent $SHELL $HOME/.profile2
Next, in your shell initialization file ($ENV for
ksh, or
~/.bashrc for
bash), place the following lines to load your
default identity only if it's not loaded already:
# Make sure we are attached to a tty
if /usr/bin/tty > /dev/null
then
# Check the output of "ssh-add -l" for identities.
# For SSH2, use the line:
# ssh-add2 -l | grep 'no keys' > /dev/null
#
ssh-add1 -l | grep 'no identities' > /dev/null
if [ $? -eq 0 ]
then
# Load your default identity. Use ssh-add2 for SSH2.
ssh-add1
fi
fi