chiark / gitweb /
bin/start-ssh-agent: Export `SSH_AUTH_SOCK' in just one place.
[profile] / bin / start-ssh-agent
1 #! /bin/sh
2
3 set -e
4 usage="Usage: $0 [-bc] [COMMAND [ARGS...]]"
5
6 ### Parse options
7 case "${SHELL-/bin/sh}" in
8   *csh*) style=csh;;
9   *) style=sh;;
10 esac
11 force=nil chosen= commands=
12 while [ $# -gt 0 ]; do
13   case "$1" in
14     -h | --help) echo "$usage"; exit 0 ;;
15     -c | --cshell | --tcsh) style=csh chosen=t ;;
16     -b | --bourne | --bash | --zsh) style=sh chosen=t ;;
17     -f | --force) force=t ;;
18     --) shift; break ;;
19     -*) echo >&2 "$usage"; exit 1 ;;
20     *) break ;;
21   esac
22   shift
23 done
24 [ $# -gt 0 ] && style=commands
25 case $chosen,$style in
26   t,commands)
27     echo >&2 "$0: output style and commands? you're odd"
28     exit 1
29     ;;
30 esac
31
32 ## Some useful variables.
33 hostname=${HOST-$(hostname)}
34 user=${USER-${LOGNAME-$(id -un)}}
35 dir=$TMPDIR/.ssh-agent.$hostname.$user
36 socket=$dir/sock; pid=$dir/pid
37 export SSH_AUTH_SOCK
38
39 ### Should I start a new agent?
40 case "$force,$SSH_AUTH_SOCK" in
41   t,* | nil,)
42     foundp=nil
43     ;;
44   *)
45     foundp=t
46     set +e; ssh-add -l >/dev/null 2>&1; rc=$?; set -e
47     [ $rc -ge 2 ] && foundp=nil
48     ;;
49 esac
50
51 ### If so, do that
52 case $foundp in
53   nil)
54     mkdir -p -m700 "$dir"
55     SSH_AUTH_SOCK=$socket
56     set +e; ssh-add -l >/dev/null 2>&1; rc=$?; set -e
57     if [ $rc -ge 2 ]; then
58       if [ -f "$pid" ]; then
59         kill $(cat "$pid") >/dev/null 2>&1 || :
60       fi
61       rm -f "$socket" "$pid"
62       (cd /; exec ssh-agent -d -a "$socket" >/dev/null 2>&1)&
63       echo $! >"$pid"
64       SSH_AUTH_SOCK=$socket
65     fi
66     ;;
67 esac
68
69 ### Run a program, or export the details
70 case $style in
71   sh) echo "SSH_AUTH_SOCK='$SSH_AUTH_SOCK'; export SSH_AUTH_SOCK" ;;
72   csh) echo "setenv SSH_AUTH_SOCK '$SSH_AUTH_SOCK'" ;;
73   commands) exec "$@" ;;
74 esac