1

I have a script test

#! /bin/bash

sleep 60
echo hello

I ran it by setting it executable and ./test, and while it was running the sleep command, I changed it to

#! /bin/bash

sleep 60
echo hello!!

The output is hello!!. I wonder why not hello?

How can I make it output hello regardless of later change?

  • 1
    Notice in general, DO NOT modify a running shell script. As it saves the file position while it is executing the file and thus you could SERIOUSLY affect what is running. You were lucky in the position you choose to edit the file. – mdpc Nov 27 '14 at 0:49
4

This is the solution that will work for your case.

Break your script into functions, and each time a function is called you source it from a separate file. Then you could edit the files at any time and your running script will pick up the changes next time it gets sourced.

foo() {
  source foo.sh
}
foo

Testing

I have created 2 scripts say callee.sh and called.sh as below.

#The contents of callee.sh script is as below. 
callee.sh

foo() {
  source called.sh
}
foo

#The contents of called.sh script is as below. 
called.sh

#! /bin/bash

sleep 60
echo hello

Now, I execute callee.sh which in turn calls my called.sh script. Basically, called.sh is the script which we will be changing dynamically.

Now, when callee.sh is getting executed, I open another shell and change the contents as,

#! /bin/bash

    sleep 60
    echo hello
    echo "I added more contents here"

Now, in the first shell from which I called the script callee.sh after the sleep is over, the output I get is,

hello

As you could see, I did not get the I added more contents here in my output which is what the desired end result is.

References

https://stackoverflow.com/a/3399850/1742825

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