How to make shell scripts reliable for a source that changes at startup

People noticed that if you change the source of the shell script, all currently running instances will fail?

This, in my opinion, is very bad; this means that I have to make sure all instances of the script are stopped before the changes are made. My preference would be that existing scripts continue to work with the old source code, and new instances use new code (for example, what happens for perl and python programs).

Do people have any good workarounds for this behavior other than pre-copying the shell script into tempfile and running from this?

Thanks, / YGA

+10
shell
Feb 18 2018-10-18T00
source share
3 answers

A very small addition to the other answers below:

#!/bin/sh { # Your stuff goes here exit } 

At the end, exit is important. Otherwise, at the end of the script file, you can still access to see if there are more lines to interpret.

This question was later reorganized here: Can a shell script indicate that its lines are first loaded into memory?

+16
Mar 01 '10 at 19:24
source share
— -

Make sure that the shell must parse the entire file before executing any of them:

 #!/bin/ksh { all the original script here } 

This is a trick.

By the way, with Perl (and I assume Python), the program analyzes the entire file before executing it, exactly as recommended here. That is why you usually do not encounter a problem with Perl or Python.

+2
Feb 18 '10 at 0:17
source share

The desired behavior may not be possible, depending on the complexity of the shell scripts that are involved.

If the full shell script is contained in a file with one source code, and this file is fully parsed before execution, then the shell script is usually safe from changes to the copy on disk at runtime. Wrapping all executable statements into a function (or a series of functions), as a rule, will achieve its goal.

 #!/bin/sh doit() { # Stuff goes here } # Main doit 

The difficulty arises when the shell script “includes” other shell scripts (for example, “.” Or “source”). If they include wrapped functions, they are not parsed until this statement is reached in the thread of execution. This makes the shell script vulnerable to changes to this external code.

In addition, if the script shell runs any external program (for example, a script shell, a compiled program, etc.), this result is not fixed until this execution point is reached (if at all).

 #!/bin/sh doit() { if [[some_condition]] ; then resultone=$(external_program) fi } # Main doit 
+2
Feb 18 2018-10-18T00
source share



All Articles