使用 if 命令获取文件夹的所有者

Eri*_*aid 2 shell bash shell-script

我希望能够防止人们在我的脚本中意外删除系统的关键文件,有谁知道如何使用该语句来查找文件夹的所有者?

Sté*_*las 5

find . -prune -user "$(id -u)"
Run Code Online (Sandbox Code Playgroud)

.如果当前目录归您所有,则将打印。

你可以这样做:

find . -prune -user "$(id -u)" -exec some command \;
Run Code Online (Sandbox Code Playgroud)

或者:

if [ -n "$(find . -prune -user "$(id -u)")" ]; then
  some command
fi
Run Code Online (Sandbox Code Playgroud)

some command仅当当前目录归您所有时才运行。

test大多数aka实现(包括、、、和shell[中的内置之一)也具有(大写 O):zshbashkshdashyashbosh-O

if [ -O . ]; then
  some command
fi
Run Code Online (Sandbox Code Playgroud)

shellzsh还具有Uglob 限定符来选择您拥有的文件。find因此,可以采用与此类似的方法:

if ()(($#)) .(NU); then
  some command
fi
Run Code Online (Sandbox Code Playgroud)

要检索当前目录所有者的 id,POSIXly,您可以执行以下操作:

ownerid=$(LC_ALL=C ls -lnd . | awk '{print $3}')
Run Code Online (Sandbox Code Playgroud)

或者,使用 的zsh内置stat

stat -LH stat . && ownerid=$stat[uid]
Run Code Online (Sandbox Code Playgroud)

或者使用 GNU find

ownerid=$(find . -prune -printf %U)
Run Code Online (Sandbox Code Playgroud)

或者使用 GNU stat

ownerid=$(stat -c %u .)
Run Code Online (Sandbox Code Playgroud)

或者,对于 BSD stat

ownerid=$(stat -f %u .)
Run Code Online (Sandbox Code Playgroud)

获得该信息后$ownerid,您可以将其与您可以使用的 shell 进程的有效用户 ID 进行比较"$(id -u)"。一般来说,使用用户 ID 比使用用户名更好,因为帐户数据库中每个用户 ID 可以有多个用户名(这样就无需查询用户数据库)。