Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a shell script indicate that its lines be loaded into memory initially?

UPDATE: this is a repost of How to make shell scripts robust to source being changed as they run

This is a little thing that bothers me every now and then:

  1. I write a shell script (bash) for a quick and dirty job
  2. I run the script, and it runs for quite a while
  3. While it's running, I edit a few lines in the script, configuring it for a different job
  4. But the first process is still reading the same script file and gets all screwed up.

Apparently, the script is interpreted by loading each line from the file as it is needed. Is there some way that I can have the script indicate to the shell that the entire script file should be read into memory all at once? For example, Perl scripts seem to do this: editing the code file does not affect a process that's currently interpreting it (because it's initially parsed/compiled?).

I understand that there are many ways I could get around this problem. For example, I could try something like:

cat script.sh | sh

or

sh -c "`cat script.sh`"

... although those might not work correctly if the script file is large and there are limits on the size of stream buffers and command-line arguments. I could also write an auxiliary wrapper that copies a script file to a locked temporary file and then executes it, but that doesn't seem very portable.

So I was hoping for the simplest solution that would involve modifications only to the script, not the way in which it is invoked. Can I just add a line or two at the start of the script? I don't know if such a solution exists, but I'm guessing it might make use of the $0 variable...

like image 692
Anonymous Avatar asked Feb 25 '10 19:02

Anonymous


1 Answers

The best answer I've found is a very slight variation on the solutions offered to How to make shell scripts robust to source being changed as they run. Thanks to camh for noting the repost!

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

This ensures that all of your code is parsed initially; note that the 'exit' is critical to ensuring that the file isn't accessed later to see if there are additional lines to interpret. Also, as noted on the previous post, this isn't a guarantee that other scripts called by your script will be safe.

Thanks everyone for the help!

like image 69
Anonymous Avatar answered Sep 26 '22 05:09

Anonymous