The below command works fine from my localhost and I get the desired output. See below

$ ssh -o ConnectTimeout=7  -o BatchMode=yes [email protected] "echo WORKS;exit"

Now, I put this command in a script file test.sh having sufficient execution privileges

$ cat test.sh
segment=$(ssh -o ConnectTimeout=7  -o BatchMode=yes [email protected] "echo WORKS;exit")
echo "SEGMENT $segment"

I don't get the desired output. Infact I get the below error:

$ ./test.sh
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

I was expecting


Now, the Permission denied error goes away but

Can you please suggest what could be the issue ?

  • How are you running your script (crontab?)? How are you authenticating with the remote system (public key in a ssh-agent?)?
    – Kusalananda
    Sep 24, 2020 at 8:37
  • @Kusalananda i updated my original post to answer your question.
    – Ashar
    Sep 24, 2020 at 8:51
  • I got the problem. alias ssh with private key ssh -i /<path_to_private_key> was set is what it was working on local command line but in the script I had to specify the private key explicitly.
    – Ashar
    Sep 24, 2020 at 8:58
  • Yes, aliases are not expanded in bash scripts. See e.g. unix.stackexchange.com/questions/368246/…
    – Kusalananda
    Sep 24, 2020 at 9:04
  • @Ashar you should write you solution as an answer, this might help someone in same situation.
    – Archemar
    Sep 24, 2020 at 9:14

1 Answer 1


The issue was that I used an alias

alias ssh=ssh -i /app/private_key

stored in the user profile. However, this setting doesn't take effect in a shell script (see here e.g.), so I had to explicitly call

ssh -i app/private_key

in the script. This resolved the issue.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .