2

I have a script I made for work that will call a function that takes an argument. I use the arguments to ssh into our servers. My question is: Is there a way to call the method so that if/when I get disconnected from our servers, It will automatically call the script? So for example, I can ssh into one of our servers. We have a reverse-ssh tunnel set up so after an hour the connection closes. I want it so that after the disconnection, the script will be called again prompting for a hostname.

#!/bin/bash
echo "Provide hostname: "
read host

createSSHFunction()
{
    arg1=$1
    ssh $host
}
createSSHFunction $host
3
  • 1
    "I want it so that after the disconnection, the script will be called again prompting for a hostname." -> You're not asking to call a function recursively then. Commented Jul 21, 2014 at 18:16
  • Yes sorry for the confusion, I made an edit to the question Commented Jul 21, 2014 at 18:16
  • Why was this question downvoted???!!!! Commented Jul 22, 2014 at 15:55

2 Answers 2

2

Recursion is rarely the answer to anything :-)

What you are trying to do can be done via a simple loop

while :; do
  ssh $host
done

Whenever ssh exits, the script will go to the next iteration of the loop, and re-execute it.

In while :, the : is a noop command that always returns a true value, so the while will never end. If you need some way of terminating the loop, you'll need to figure out what that criteria is, and test for it.

4
  • I tried that and I get an infinite loop... Commented Jul 21, 2014 at 18:03
  • Any recursion would also be infinite ;) Commented Jul 21, 2014 at 18:06
  • @ryekayo that's what you asked for, "when I get disconnected from our servers, It will automatically call the function". If you want to break the loop, you need to specify criteria for doing so. Commented Jul 21, 2014 at 18:10
  • Sorry let me edit the question a bit further Commented Jul 21, 2014 at 18:11
1

You'll need to loop infinitely, but prevent the script from running again when you are done.

while ((1)); do script.sh; sleep 3; done

The three second sleep gives you an opportunity to break the loop. When you're done with ssh, exit. In three seconds, the script will start again. If you don't want that to happen, Ctrl-C will stop the loop.

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.