chiark / gitweb /
bin/start-ssh-agent: Style tweaking of `case' statements.
[profile] / bin / start-ssh-agent
CommitLineData
285a1386
MW
1#! /bin/sh
2
3set -e
4usage="Usage: $0 [-bc] [COMMAND [ARGS...]]"
5
6### Parse options
7case "${SHELL-/bin/sh}" in
8 *csh*) style=csh;;
9 *) style=sh;;
10esac
11force= chosen= commands=
12while [ $# -gt 0 ]; do
13 case "$1" in
c388de2b
MW
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 ;;
285a1386
MW
21 esac
22 shift
23done
24[ $# -gt 0 ] && style=commands
25case $chosen,$style in
26 t,commands)
27 echo >&2 "$0: output style and commands? you're odd"
28 exit 1
29 ;;
30esac
31
32### Should I start a new agent?
33case "$force,$SSH_AUTH_SOCK" in
34 t,* | ,)
35 start=t
36 ;;
37 *)
38 start=
b52d5e17 39 set +e; ssh-add -l >/dev/null 2>&1; rc=$?; set -e
285a1386
MW
40 [ $rc -ge 2 ] && start=t
41 ;;
42esac
43
44### If so, do that
45if [ "$start" ]; then
46 hostname=${HOST-$(hostname)}
47 user=${USER-${LOGNAME-$(whoami)}}
b52d5e17 48 dir=$TMPDIR/.ssh-agent.$hostname.$user; socket=$dir/sock; pid=$dir/pid
285a1386
MW
49 mkdir -p -m700 "$dir"
50 SSH_AUTH_SOCK=$socket; export SSH_AUTH_SOCK
b52d5e17 51 set +e; ssh-add -l >/dev/null 2>&1; rc=$?; set -e
285a1386
MW
52 if [ $rc -ge 2 ]; then
53 if [ -f "$pid" ]; then
54 kill $(cat "$pid") >/dev/null 2>&1 || :
55 fi
56 rm -f "$socket" "$pid"
57 (cd /; exec ssh-agent -d -a "$socket" >/dev/null 2>&1)&
58 echo $! >"$pid"
59 SSH_AUTH_SOCK=$socket; export SSH_AUTH_SOCK
60 fi
61fi
62
63### Run a program, or export the details
64case $style in
c388de2b
MW
65 sh) echo "SSH_AUTH_SOCK='$SSH_AUTH_SOCK'; export SSH_AUTH_SOCK" ;;
66 csh) echo "setenv SSH_AUTH_SOCK '$SSH_AUTH_SOCK'" ;;
67 commands) exec "$@" ;;
285a1386 68esac