1

I have a script.sh file which checks for loaded SSH agent and adds a key.

If I run this script directly, it works but if I run it via some worker it doesn't unless I do those changes:

This works:

#!/bin/bash -e

printf "<<<<< Start SSH agent and Github deploy key >>>>>\n"
if ps -p $SSH_AGENT_PID > /dev/null
then
  printf "<<<<< ssh-agent is already running >>>>>\n"
else
  eval `ssh-agent -s`
fi
ssh-add $deploy_key_path

But his doesn't work:

#!/bin/bash -e

if [ $(ps ax | grep [s]sh-agent | wc -l) -gt 0 ] ; then
  printf "<<<<< ssh-agent is already running >>>>>\n"
else
  eval `ssh-agent -s`
fi
ssh-add $deploy_key_path

The error says ...failed. Exit Code: 2(Misuse of shell builtins).. which happens at the line ssh-add $deploy_key_path

When checking the reserved Bash error codes I see:

2   Misuse of shell builtins    empty_function() {} Missing keyword or command
6
  • 1
    I don't see how you could get the error on that line. I think it could only happen on the eval line.
    – Barmar
    Commented Apr 11, 2022 at 17:23
  • 1
    Replace eval with echo to see what it's trying to evaluate.
    – Barmar
    Commented Apr 11, 2022 at 17:26
  • 1
    I'd recommend running your script through shellcheck.net Commented Apr 11, 2022 at 17:27
  • 2
    BTW, grep ... | wc -l can be combined into grep -c ...
    – Barmar
    Commented Apr 11, 2022 at 17:33
  • 1
    Where do you set deploy_key_path? If it's set by eval, then the line that uses it should be in the else.
    – Barmar
    Commented Apr 11, 2022 at 17:33

1 Answer 1

2

Here is one reasonable way I'd use ssh-agent and ssh-add, minimizing security risks by not keeping keys unlocked more than it is strictly needed within the script.

#!/usr/bin/env sh

# Do not leave key unlocked after execution of this script
trap 'ssh-add -d "$deploy_key_path"' EXIT INT

# If ssh-agent has an auth socket or has a PID
if [ -S "$SSH_AUTH_SOCK" ] || ps -p "$SSH_AGENT_PID" >/dev/null 2>&1; then
  printf '<<<<< ssh-agent is already running >>>>>\n'
else
  # Do not use back-ticks as it is legacy obsolete
  eval "$(ssh-agent -s)"
fi

# Do not leave key unlocked more than 5 minutes
ssh-add -t 600 "$deploy_key_path"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.