栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

shell脚本修改文件名和权限

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

shell脚本修改文件名和权限

分享一个脚本,背景:公司要把项目文件中的.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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/828077.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号