下面的命令用来获得文件或目录的Owner:
/usr/bin/stat -c "%U" $file
或者笨一点的办法
ls -l . | grep $filename | awk '{print $3}'
要得到文件的全路径可以用命令 readlink -f $file
。
readlink命令用于解析symbol link真正的指向。它也可以用于普通文件。
这里得到的路径实际上是canonical file name。
如果不是超级用户(root),但却有文件所有者(File Owner)的rsh权限,可以如下操作:
find $dir_to_delete -depth -type d -maxdepth 5 -exec rm-with-owner {} \;
上面的"rm-with-owner"的内容如下:
#!/bin/sh file=$1 owner=`/usr/bin/stat -c %U $file` file_fullpath=`readlink -f $file` echo rsh -l $owner localhost rm -rf $file_fullpath if [ $# -eq 1 ] then rsh -l $owner localhost rm -rf $file_fullpath fi
上面的代码需要对每个文件进行rsh操作,所以效率是比较低的。使用过程中改进如下。
主要思路是先找出所有文件的onwer list,再批量删除,从而减少rsh的次数。
#!/bin/sh if [ $# -lt 2 ] then echo "Usage: $0 <dir_to_delete> [all|owner|username]" exit fi dir_delete=$1 dir_fullpath=`readlink -f $dir_delete` rsh_host=localhost if [ $2 = "all" ] then for user in `find $dir_delete -type d -maxdepth 5 -exec stat -c %U {} \; | sort -u` do $0 $dir_fullpath $user done exit elif [ $2 = "owner" ] then rsh_user=`/usr/bin/stat -c %U $file` else rsh_user=$2 fi rsh -l $rsh_user $rsh_host /bin/rm -rf $dir_fullpath