Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an R function to change file ownership?

Tags:

linux

r

chown

How could I change the ownership of files from R? I suppose I could use system and call chown directly against a string, but I am wondering if there is a better way.

like image 998
wdkrnls Avatar asked Oct 21 '25 14:10

wdkrnls


1 Answers

As was already mentioned in the comments, the function Sys.chown() does not exist. I have written a function that does the job for me. Compared to other functions of the type Sys.*, this one has the disadvantage that chown requires sudo. Using sudo with R's system() does not work, but this answer suggests the use of gksudo, which works fine for me.

So this is the function definition:

Sys.chown <- function(paths, owner = NULL, group = NULL) {

   # create string for user:owner
   if (!is.null(group)) {
      og <- paste0(owner, ":", group)
   } else {
      og <- owner
   }

   # create string with files
   files <- paste(paths, collapse = " ")

   # run command
   system(paste("gksudo chown", og, files))

   invisible()
}

The first part creates the string that sets the owner and the group, which should be of the form owner:group. However, it is possible to omit one or both of these argument and the function takes care of all the possibilities.

Next comes the part where all the file names that have been supplied to paths are put into a single string.

And finally, system() is used to do the actual call of chown. gksudo will open a dialog window and ask for the password. Unfortunately, one has to type the password every time.

There are several useful options to chown and a better implementation of Sys.chown() should probably be able to handle some of them.

Example

system("ls -l")
## total 0
## -rw-rw-r-- 1 user1 user1 0 Jan 21 19:32 test2.file
## -rw-rw-r-- 1 user1 user1 0 Jan 21 19:32 test.file
Sys.chown("test.file", owner = "user2")
Sys.chown("test2.file", group = "user2")
system("ls -l")
## total 0
## -rw-rw-r-- 1 user1 user2 0 Jan 21 19:32 test2.file
## -rw-rw-r-- 1 user2 user1 0 Jan 21 19:32 test.file
Sys.chown("test.file", owner = "user1", group = "user2")
system("ls -l")
## total 0
## -rw-rw-r-- 1 user1 user2 0 Jan 21 19:32 test2.file
## -rw-rw-r-- 1 user1 user2 0 Jan 21 19:32 test.file
Sys.chown(dir(), owner = "user1", group = "user1")
system("ls -l")
## total 0
## -rw-rw-r-- 1 user1 user1 0 Jan 21 19:32 test2.file
## -rw-rw-r-- 1 user1 user1 0 Jan 21 19:32 test.file
like image 152
Stibu Avatar answered Oct 23 '25 06:10

Stibu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!