2

I have a bash script I'm using to connect to a remote server via ssh. That works, however I want the script to immediately pass the command of cd /some/dir after connecting. That doesn't seem to be working. Here's my code:

#!/bin/bash
echo "SSHing.."
ssh -i ~/.ssh/some-site.pem xxx@yyy.com
cd /some/dir        
read

How can I have the cd command be executed right after SSH connection is established?

Ali
  • 261,656
  • 265
  • 575
  • 769
  • 1
    This thread [linux-execute-command-remotely][1] might be helpful to you. Did you check it? [1]: http://stackoverflow.com/questions/5162568/linux-execute-command-remotely – Srini Feb 05 '13 at 08:57

4 Answers4

10

There are two easy ways to execute commands via SSH from inside the script:

1) ssh user@host 'command'

2)

ssh user@host <<<EOF
command1
command2
<...>
commandn
EOF
KBart
  • 1,580
  • 10
  • 18
  • 1
    #2 gives the error `Pseudo-terminal will not be allocated because stdin is not a terminal.` – Ali Feb 05 '13 at 09:52
  • 1
    @Click Upvote see http://stackoverflow.com/questions/7114990/pseudo-terminal-will-not-be-allocated-because-stdin-is-not-a-terminal for a similar problem, I wouldn't explain better. – KBart Feb 05 '13 at 10:55
  • 1
    I was getting a '-bash: line 1: EOF: command not found' error but changed << – jsquirrelz Sep 25 '13 at 06:00
6

Normally you'd just edit your ~/.profile on the remote machine.

If that is not an option, you could do something like this:

ssh -t theserver.com 'cd /some/dir && bash -i'
rtytgat
  • 488
  • 2
  • 10
0

You can use the following command

ssh user@watevr <the_cmd_to_be_executed>
Antarus
  • 1,573
  • 2
  • 15
  • 32
0

You can try this :

ssh abc@hostname :/pathto/specific directory
Rudra
  • 711
  • 7
  • 13
  • 31