Is there an R function to change file ownership?

痞子三分冷 提交于 2019-12-10 22:44:32

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/34927257/is-there-an-r-function-to-change-file-ownership

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!