Search code examples
bashssh-agent

Why isn't my bash function executing when I know that the definition is processed?


I have the following in my bashrc:

# Set up ssh-agent
SSH_ENV="$HOME/.ssh/environment"

function start_agent {
    echo "Initializing new SSH agent..."
    /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
    echo succeeded
    chmod 600 "${SSH_ENV}"
    . "${SSH_ENV}" > /dev/null
    /usr/bin/ssh-add;
}

# Source SSH settings, if applicable
if [ -f "${SSH_ENV}" ]; then
    . "${SSH_ENV}" > /dev/null
    #ps ${SSH_AGENT_PID} doesn't work under cywgin
    ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
        start_agent;
    }
else
    start_agent;
fi

I know that start_agent is defined because I can type start_agent on the command-line and it "does the right thing". The problem is that I'm expecting start_agent to be executed on login and it is not executing. But I know that the control flow is passing through it because the function is defined.


Solution

  • Try just:

    if [ condition ]; then
      echo "then branch "
      start_agent
    else
      echo "else branch"
      start_agent
    fi
    

    if this works then it's your ps -ef .... line that is not doing what you expect.

    Additionally you can try what shellter suggests set -vx for an "echo style" debug.