3

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.

wdkrnls
  • 4,548
  • 7
  • 36
  • 64
  • Some system related functions are `Sys.*` (example `Sys.chmod()`) But there is no one for `chown` in base. – jogo Jan 21 '16 at 15:10
  • You can type the command into `?system`, but you'll have to cater it to the current OS, I guess. – Frank Jan 21 '16 at 15:15

1 Answers1

2

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
Community
  • 1
  • 1
Stibu
  • 15,166
  • 6
  • 57
  • 71
  • afaik, you can use sudo with R's system command, you need to do `sudo -ks ` and then submit the password via input. But you should be careful with this, since then the password will be in the command, which could be viewable from ps...etc... – Shape Jan 02 '18 at 19:20