Ubuntu

如何使用 xargsexec 以特定值遞歸移動<user_id>:<group_id>

  • October 27, 2020

我正在嘗試遞歸地移動<user_id>:<group_id>通過使用xargsor的特定值exec。我很難將輸出從函式傳遞find到變數stat。我正在執行 Ubuntu 20.04。

find . -type f,d | xargs chown $(($(stat --printf %u {})+1)):$(($(stat --printf %g {})+1)) {}

stat: cannot stat '{}': No such file or directory

stat: cannot stat '{}': No such file or directory

chown: cannot access '{}': No such file or directory

我會zsh在這裡使用:

#! /bin/zsh -
# enable the stat builtin (which btw predates GNU stat by several years)
zmodload zsh/stat || exit

# enable chown (and other file manipulation builtin)
zmodload zsh/files || exit
ret=0

for f (./**/*(DN.,/) .) {
 stat -LH s $f && # store file attributes in the $s hash/associative array
   chown $((s[uid] + 1)):$((s[gid] + 1)) $f || ret=$?
}
exit $ret # report any error in stat()ing or chown()ing files

(其中Ddotfile 是包含隱藏文件,N對於 nullglob 是如果沒有找到文件.,/是正常文件或目錄,則不認為它是錯誤的-type f,d)。

如果在像 Ubuntu 20.04 這樣的 GNU 系統上,你也可以這樣做:

find . -type f,d -printf '%p\0%U\0%G\0' | # print path, uid, gid as 3
                                         # nul-delimited records
 gawk -v RS='\0' -v ORS='\0' '{
   file = $0; getline uid; getline gid
   print (uid+1) ":" (gid+1); print file}' | # outputs a uid+1:gid+1
                                             # and path record for each file
 xargs -r0n2 chown # pass each pair of record to chown

但是因為這涉及到chown每個文件執行一個(在zsh方法中,我們chown在模組中執行內置zsh/files),所以效率會低很多。

引用自:https://unix.stackexchange.com/questions/616423