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
  • 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. – goldilocks Jul 21 '14 at 18:16
  • Yes sorry for the confusion, I made an edit to the question – ryekayo Jul 21 '14 at 18:16
  • Why was this question downvoted???!!!! – ryekayo Jul 22 '14 at 15:55
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.

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.

  • I tried that and I get an infinite loop... – ryekayo Jul 21 '14 at 18:03
  • Any recursion would also be infinite ;) – goldilocks Jul 21 '14 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. – Patrick Jul 21 '14 at 18:10
  • Sorry let me edit the question a bit further – ryekayo Jul 21 '14 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.