chmod命令用于修改文件mode,即权限.有时我们需要递归处理,加上-R选项即可.但是有时我们需要这种情况: 普通文件和目录文件设置不同的mode. 最常见的情况是从windows下烤的工程项目要部署到linux下, 假设服务器是tomcat, 于是我们必须修改工程权限,要能cd进去,目录必须有可执行权限,但我们又不希望普通源码文件也加上莫名其妙的可执行权限.
下面我的脚本直接调用了chmod,只是多了几个判断而已! 实在不知道怎么写标题,改进还是改退? 或者根本不能称为改进,而是重新封装了下?
#!/bin/bash
declare -f op
declare -f showHelp
# 逐一处理文件
op()
{
while [ "$#" -gt 0 ] # 还有待处理参数
do
file="$1"
if [ ! -e "$1" ]
then
echo "$1 does not exists."
shift # 处理下一个参数
continue
fi
if [ ! -d "$1" ]
then
chmod -c "$filemod" "$1" || echo "chmod $filemod $1 fail!"
else
chmod -c "$dirmod" "$1" || echo "chmod $dirmod $1 fail!"
if [ "$recursive" = "1" ] # 若递归,则继续递归调用op函数
then
for subfile in $1/*
do
[ -e "$subfile" ] || continue # 这个要注意,防止当不存在文件时,*不会展开
op "$subfile"
done
fi
fi
shift #处理下一个参数
done
}
# 显示帮助信息
showHelp()
{
cat <<EOF
usage: $0 [-r | -R] [-f filemod] [-d dirmod] file1 file2 ...
for example: $0 -r -f a+r -d a+x
EOF
exit 0
}
test()
{
while [ $# -gt 0 ]
do
echo "$1"
shift
done
}
opt=0 # 记录参数选项个数
while getopts ":rRf:d:hH" arg
do
case $arg in
"h" | "H")
showHelp
;;
"r" | "R")
recursive=1
((opt+=1))
;;
"f")
filemod=$OPTARG
((opt+=2))
;;
"d")
dirmod=$OPTARG
((opt+=2))
;;
":")
echo "No argument value for option $OPTARG"
exit 1
;;
"?")
showHelp
;;
*)
echo "Unkown error while processing options"
exit 1
;;
esac
done
# 去掉选项参数
while [ $opt -gt 0 ]
do
shift
((opt-=1))
done
# 设置变量默认值
filemod=${filemod:-"664"}
dirmod=${dirmod:-"775"}
recursive=${recursive:-"0"}
# 主程序入口, 如果有文件需要处理,则调用op,否则直接退出
if [ $# -gt 0 ]
then
op $@
else
showHelp
fi
2013年8月24日 14:05
chmod u=rwX,g=rX,o=rX -R
2013年8月26日 20:00
@依云:针对目录/文件 的执行权限这样最好不过了.
2013年8月27日 01:03
@依云: 呃,一直没注意过有大写 X 这个符号…… Orz 还想说你以前教的 find -type d 和 find -type f 呢 =_=
2013年8月27日 14:22
@λ: 比较简单的方法是
for f in `find .`
do
if [ -d ]
then
something
fi
done
2013年8月27日 16:03
@krystism: 也是比较容易出问题的方法。
2013年8月28日 09:20
@krystism: 呃,这不算简单吧,find 本身就可以过滤出目录并执行命令,现在你获取了所有文件名后再判断,至少效率上是过不去了……
2013年9月16日 22:00
chmodd ()
{
find "$1" -type d -exec chmod 755 {} \;
}
2024年2月21日 21:20
Nice post. I was checking constantly this blog and I am impressed! Extremely helpful information specially the last part I care for such info a lot. I was seeking this particular information for a very long time.