6

I have the following bash script test.sh

#!/bin/bash
ssh -o "StrictHostKeyChecking no" user@$1
#do some stuff
exit

However if I run this script ./test.sh I need to enter ctrl+d to get out of the ssh session and it appears as if the exit command is not working the way I intended.

Is there any way I can exit this ssh session that was created from this bash script?

1 Answer 1

16

You may want to code a here document

#!/bin/bash
ssh -o "StrictHostKeyChecking no" user@$1 << ENDHERE
   here do some remote stuff
   also here
   exit
ENDHERE

If you code <<-ENDHERE the initial spaces or tabs in each line of the here document are suppressed. Parameters (like $foo) are substituted unless you code <<\ENDHERE, and the ENDHERE can actually be any word, conventionally in capitals.

Read the Advanced Bash Scripting guide (which does have some imperfections)

Sign up to request clarification or add additional context in comments.

3 Comments

also use ssh -T if you don't want a tty
if you want to exit the shell script if the ssh session is interrupted, add exec before ssh.
There are some problems with the HERE Implementation. For one, you can't sudo through HERE documentation. See the end of thornelabs.net/2013/08/21/… for more information.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.