Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make shell scripts robust to source being changed as they run

Tags:

Have people noticed that if you modify the source of a shell script, any instances that are currently running are liable to fail?

This in my opinion is very bad; it means that I have to make sure all instances of a script are stopped before I make changes. My preferred behavior would be that existing scripts continue running with old source code and that new instances use the new code (e.g. what happens for perl and python programs).

Do folks have any good workarounds for this behavior, other than pre-copying the shell script to a tempfile and running from that?

Thanks, /YGA

like image 658
10 revs, 7 users 53% Avatar asked Feb 18 '10 00:02

10 revs, 7 users 53%


People also ask

Can you edit a shell script while it is running?

The shell is not like other scripting languages. The shell reads and executes commands one by one, so the simple answer is "yes, editing a running script can affect it", but it's important to understand the details.

How are shell scripts executed?

A shell script is a sequence of commands for which you have a repeated use. This sequence is typically executed by entering the name of the script on the command line.

What does sourcing a bash file do?

The source command reads and executes commands from the file specified as its argument in the current shell environment. It is useful to load functions, variables, and configuration files into shell scripts. source is a shell built-in in Bash and other popular shells used in Linux and UNIX operating systems.


2 Answers

Very slight addition to the other answers:

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

The exit at the end is important. Otherwise, the script file might still be accessed at the end to see if there are any more lines to interpret.

This question was later reposted here: Can a shell script indicate that its lines be loaded into memory initially?

like image 132
Anonymous Avatar answered Sep 28 '22 11:09

Anonymous


Make sure the shell has to parse the whole file before executing any of it:

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

That does the trick.

Incidentally, with Perl (and I assume Python), the program parses the entire file before executing any of it, exactly as recommended here. Which is why you don't usually run into the problem with Perl or Python.

like image 43
Jonathan Leffler Avatar answered Sep 28 '22 13:09

Jonathan Leffler