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
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.