0

I am making a shell script and need to mark a temp file as "busy". Like if you try deleting it in your terminal it will say "Resource busy".

I want to prevent any user of any power from removing this file, until my script closes. Only my script has the authority to mark and unmark the file as busy.

Is that possible?

  • 3
    No, it's not possible. Unix semantics allow for a file to be deleted, but the inode for that file is kept until every open file descriptor on the file is closed. – chepner Jan 26 '20 at 21:17
  • 1
    In fact, it is *recommended* that you open the file, then delete it (while still keeping the file open) so that only your process can even tell it exists. (Though to be honest, I don't recall how, or if, you can perform random access on a file in a shell script.) – chepner Jan 26 '20 at 21:18
  • Take a look at the command `flock` to see it suits your needs. – Philippe Jan 26 '20 at 21:52
  • Thanks for clearing this matter up @chepner – 45breads Jan 27 '20 at 00:31
  • @Philippe I looked at this and, while a bit confusing, it's better than nothing., Thanks. – 45breads Jan 27 '20 at 00:32
  • @chepner a bit linux-specific but: https://stackoverflow.com/q/3838322/10971581 – jhnc Jan 27 '20 at 04:00
  • @jhnc The lack of seek is what I was referring to regarding random access. – chepner Jan 27 '20 at 12:39
  • @chepner `echo first >foo; exec 30>foo; rm foo; cat <&30; echo second 1>&31; cat <&30; dd if=/dev/fd/30 bs=1 count=6 skip=0 2>&-; dd if=/dev/fd/30 bs=1 count=7 skip=6 2>&-` – jhnc Jan 27 '20 at 13:58
  • Yeah, that's the point where I stop trying to write the script in shell and use another language. That's not really a seek (which is a simple addition operation on an offset); it's a full-blown read that has the side effect of advancing the file pointer. (Also, can you "seek" *backwards* with `dd`, or do you simply have to read from the beginning of the file again?) – chepner Jan 27 '20 at 14:14

1 Answers1

0

If you just want to read the file, but not updating it while it's "locked" then you could set the immutable flag on it :

[~]@ubuntu-s-1vcpu-1gb-nyc3-01  
(0) matias #> sudo chattr +i food.txt 
[~]@ubuntu-s-1vcpu-1gb-nyc3-01  
(0) matias #> lsattr food.txt 
----i---------e--- food.txt
[~]@ubuntu-s-1vcpu-1gb-nyc3-01  
(0) matias #> rm -f food.txt 
rm: cannot remove 'food.txt': Operation not permitted

Of course if you have to write to it while your script runs then this will not work and also if another user has sudo access then it can remove the immutable flag and delete it afterwards of course.

This would be more security by obfuscation rather than being bullet proof.

Matias Barrios
  • 4,674
  • 3
  • 22
  • 49