As I know, the bash script can create and write file to disk path
or /dev/shm
, but the file was accessed by root
or other user. How can I set the file's permission that only accessed by current bash script process? And I will rm
this file before exit
the bash script.
Asked
Active
Viewed 292 times
0

Victor Lee
- 2,467
- 3
- 19
- 37
-
2Maybe you can redirect a file to a given descriptor number, delete the file, and then use that descriptor with redirection... – Shawn Aug 24 '21 at 03:08
-
@Shawn THX, I will try it. – Victor Lee Aug 24 '21 at 03:17
-
2But even that won't stop `root` to get to see it / its content if they set their mind to it. – tink Aug 24 '21 at 03:18
-
Setting file permissions to 600 will stop all users except root. In general, stopping `root` needs a lot of very special actions. Selinux has been proposed (but I've never seen a water-tight solution), in the past SeOS and Autosecure could do this. But limiting root is a bad idea. Limiting access to root is a better idea. – Ljm Dullaart Aug 24 '21 at 04:58
-
@VictorLee : You can't set permissions by PID. Even if you give user permissions only, another process running by you may manipulate the file. The usual trick is - in addition to restrict the permissions - to choose a file name based on your PID, because no other process running at that time can have the same PID. Example: `touch my_file.$$`. At least accidentally overwriting this file by another process under your ID is then not so likely, but of course not impossible. – user1934428 Aug 24 '21 at 05:43
1 Answers
1
You can redirect a filename to a given descriptor number, and delete the file, and then access it through the descriptor:
#!/usr/bin/env bash
name=$(mktemp)
exec {fd}<>"$name"
rm -f "$name"
echo foo >&$fd
cat </dev/fd/$fd
Using a descriptor that's been opened for both reading and writing with <>
is tricky in bash
, see Bash read/write file descriptors — seek to start of file for the logic behind that cat
line at the end.
If you've never seen the {name}<>filename
style redirection before, it automatically assigns an unused descriptor to the file and stores its number in $name
.

Shawn
- 47,241
- 3
- 26
- 60
-
1This'll make it harder for any other process to access the file, but not impossible. For example, in Linux a root process could reach it at /proc/yourPID/fd/fdnum. – Gordon Davisson Aug 24 '21 at 04:39
-
1@GordonDavisson As pointed out in comments on the top level question, stopping root from accessing it is pretty much impossible. – Shawn Aug 24 '21 at 04:58