本次练习是检查一个文件夹(嵌套文件夹)下的文件权限以及其存在的软链接。
拿到这个任务的自己,对于脚本的编写还不是很熟练。但是很快有了解决问题的思路。
针对这一问题,目的是为了解决通过远程或者某种方式传输文件的时候,文件的权限会改变。目的就是要检测出他的改变,并且修复它。
1.首先遍历文件夹以及嵌套的文件
2.遍历出的文件判断其是否有可执行权限以及是否为文本文件,结果生成.txt文件
3.在权限损坏的文件夹下去遍历损坏的文件与2步生成的txt文件中文件匹配,看是否有可执行权限,如果没有,则赋予其执行权限。
4.在好的文件夹中检测出来的软链接会生成一个txt文件
5.通过对4中txt文件中路径的处理,保存软链接完整路径以及源文件完整路径。
6.在损坏的文件夹下同样进行匹配,发现找不到软链接路径。将给源文件生成软链接。
在这个过程中开始遇到很多问题。比如路径的截取,嵌套文件夹的读取,当然还有一些语法上的错误。但是感觉该程序的效率太低。每次比较都要进去遍历一遍整个文件夹。
附上代码:
筛选是否具有可执行权限的文本文件
#! /bin/bash
function read_dir(){
for file in `ls $1`
do
if [ -d $1"/"$file ]
then
read_dir $1"/"$file
else
file "${1}/${file}" | grep -q 'text'
retval=$?
if [ $retval -eq 0 -a -x "${1}/${file}" ]; then
# echo $1"/"$file >>xfile.txt
echo $1"/"$file | sed 's/^.*GCBS//g' >>xfile.txt
else
echo $1"/"$file "no"
fi
fi
done
}
path1=`pwd`
path2=${path1%/*}
path3=${path2%/*}
path=${path3%/*}
read_dir $path
检查损坏文件夹的文件权限:
#!/bin/bash
function read_dir(){
for file in `ls $1`
do
if [ -d $1"/"$file ]; then
read_dir $1"/"$file
else
echo $1"/"$file #得到文件名字
fi
done
}
path1=`pwd`
path2=${path1%/*}
path3=${path2%/*}
path=${path3%/*}
result=$(read_dir $path)
while read i; do
#取出可执行权限文件名字 $i
#浏览文件夹GCBS中的每个文件
for res in $result
do
# respath1=${res#*/}
# respath2=${respath1#*/}
# respath3=${respath2#*/}
# respath4=${respath3#*/ respath5=${respath4#*/}
respath=`echo $res | sed 's/^.*GCBS//g'`
if [ "$i" == "$respath" ]; then
if [ ! -x $path$respath ]; then
echo $path$respath
finallpath1=$path$respath
finallpath=${finallpath1%/*}
resfile=${respath##*/}
echo $resfile "no 与lst文件权限不一致" >> result.txt
find $finallpath -name $resfile | xargs chmod 755
echo $resfile "yes 已修复权限" >> modifyResult.txt
fi
break
fi
done
done < xfile.txt
筛选出的软链接:
#!/bin/bash
path1=`pwd`
path2=${path1%/*}
path3=${path2%/*}
path=${path3%/*}
find $path -maxdepth 20 -type l | xargs ls -l | awk '{for(i=1;i<=8;i++){$i=""};print $0}' | sed 's/^\s*//g' | sed 's/^.*GCBS//g' >>hfile.txt
对软链接的修复
#!/bin/bash
function read_dir(){
for file in `ls $1`
do
if [ -d $1"/"$file ]; then
read_dir $1"/"$file
else
echo $1"/"$file #得到文件名字
fi
done
}
path1=`pwd`
path2=${path1%/*}
path3=${path2%/*}
path=${path3%/*}
result=$(read_dir $path)
while read i; do
#取出可执行权限文件名字 $i
#浏览文件夹GCBS中的每个文件
softlink1=`echo $i | awk '{print $1}'` #软链接路径
softlink=$path$softlink1 #实际的软链接路径
# echo $softlink
#-----------处理软链接路径 end------------------------------------#
#-----------处理源文件路径 start----------------------------------#
srcpath1=`echo $i | awk '{print $3}'`
if [[ $srcpath1 == ..* ]]; then
srcfile1=${softlink%/*}
srcfile2=${srcfile1%/*} #源文件路径的上一级目录
srcfile3=${srcpath1#*/}
srcfile=$srcfile2"/"$srcfile3 #处理的源文件路径
else
srcfile1=${softlink%/*}
srcfile=$srcfile1"/"$srcpath1 #如果同级目录下
fi
# echo $srcfile
#-----------处理源文件路径 end------------------------------------#
#-----------处理是否为软链接 并修复 start------------------------#
for res in $result
do
if [ "$srcfile" == "$res" ]; then
resfile=${softlink##*/}
ln -s $srcfile $softlink
echo $resfile "yes 已修复软链接" >> modifysoft.txt
break
fi
done
done < hfile.txt