Can a shell script delete or overwrite?

#beginning of bashscript1.sh source bashscript2.sh echo $variable 

and here is the source file:

 #beginning of bashscript2.sh rm -f bashscript2.sh variable = "integer of some kind" 

How will the bash script be handled? Does it download the source file and then delete it, or does the variable matter in bash script 1?

+7
bash
source share
2 answers

On Unix-like operating systems, deleting a file is possible if it is still open. The file name will no longer exist, but the data itself remains, and any programs with an open descriptor, including bash, can continue to read (and even write) using this descriptor. Only when the last program closes its handle does the file really get deleted.

So, in a sense, yes, the shell of the script can delete itself, but in fact it will not be deleted until this script is completed.

Please note that you get different results if you overwrite a file rather than deleting it. Shells can (and do) use buffering to avoid reading one byte at a time, but the buffer is finite in size. If the contents of the file change beyond what the shell has already read in memory, it will see the new contents. You can create a simple example of this if you look at the size of the buffer for your system. On my system, it's 8 KiB. So, a shell script containing

 echo line 1 >test.sh # (8167 random characters) echo line 4 

therefore the second data block " cho line 4 ", in my system, outputs

  $ bash test.sh
 line 1
 test.sh: line 4: e: command not found

because e has already been read and the shell encountered EOF while trying to read the rest of the line.

Refresh : rici shows that with another example of overwriting a file, new content becomes familiar. Reuse:

 script="`tr 12 21 <test.sh`" env echo "$script" >test.sh echo toggle: 1 

The second line intentionally does not use the bash built-in echo command because it sometimes does not call bash to re-read the script, for comments, but exactly when it happens and is not clear to me. bash displays the newly written switch value when it hits line three. The corresponding difference between this and my previous example seems to be that here bash can look for the current position when it falls into line three, whereas in my previous example this is not possible since this position no longer exists since the file is empty.

+16
source share

Is it curiosity that you have or what you really want to get?

Anyway, I tried myself with this simple script (test_script.sh):

 rm -f test_script.sh echo "Still here!" 

and he prints Still here! , so the file was downloaded before execution. Execution is not possible a second time.

To answer your question, yes and no. The commands in the script are loaded and executed and can delete the original script file. This, of course, will make it impossible to repeat the same file, but will not affect the first execution.

+2
source share

All Articles