分享一个脚本,背景:公司要把项目文件中的.c文件修改成.cpp文件,然后解决编译问题;代码目录是通过samba共享出来,用source insight进行编辑,然而源文件权限基本是root用户,且差不多都是644,这样其他用户没有修改权限。
每次保存文件前都需要+w权限,修改完后再改回原权限。于是有了以下脚本:
# description: change c source file to cpp source file in "git mv",
# and save access right to a file, change the file's
# access right to "666" than other user can edit it.
#!/bin/sh
if [ $# -ne 1 ]; then
echo "$0 directory"
exit 0
fi
cd $1
if [ $? -ne 0 ];then
exit 1
fi
if [ -f accessRightsRecords ]; then
rm -rf accessRightsRecords
fi
touch accessRightsRecords
for files in `ls`
do
if [ -f ${files} ]; then
fileName=${files%.*} # get file name
postFix=${files##*.} # get file postfix
#echo ${fileName} ${postFix}
if [ ${postFix} = "c" ]; then # if c source file
accessRights=`stat -c %a ${files}` # get access rights in octal
echo ${files} ${accessRights}
cppFile=${fileName}.cpp
git mv ${files} ${cppFile} # change c to cpp
if [ -n accessRights ]; then # access rights not nil
echo ${cppFile} ${accessRights} >> accessRightsRecords # save original access right to a file
chmod 666 ${cppFile} #change the access right
fi
elif [ ${postFix} = "cpp" ]; then
accessRights=`stat -c %a ${files}` # get access rights in octal
echo ${files} ${accessRights} >> accessRightsRecords
chmod 666 ${files}
fi
fi
done
脚本跟一个参数(参数为目录,只支持一层目录,没有实现递归修改),功能为:
1,找到.c文件,然后用git mv 修改成.cpp文件
2,将文件名及文件的权限(8进制形式)保存到一个文件时,方便用脚本恢复其权限
3,修改文件权限为666
恢复权限的脚本很简单:从文件里按行读取,得到文件名和权限,再用chmod修改其权限。
# description: recover access right to the file
#
#!/bin/sh
if [ $# -ne 1 ]; then
echo "$0 directory"
exit 0
fi
cd $1
# file not exist, exit
if [ ! -e accessRightsRecords ]; then
echo "can't find accessRightsRecords"
exit 1
fi
cat accessRightsRecords | while read line
do
cppFile=`echo ${line} | awk '{print $1}'` # get the file name
accessRights=`echo ${line} | awk '{print $2}'` # get the access right
echo ${cppFile} ${accessRights}
if [ -e ${cppFile} ]; then # file exist
chmod ${accessRights} ${cppFile}
fi
done
rm -rf accessRightsRecords
版权声明:本文为tianyexing2008原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。