您的位置:首页 > 运维架构 > Shell

shell 编程实例学习

2016-04-28 20:13 706 查看

1 删除普通空文件

当前目录下 新建 rm_empty_file.sh ,运行后删除当前目录下的空文件

#!/bin/bash

ls > files

for file in `cat files`
do
if [ ! -s $file ]
then
rm -i $file
fi
done

rm -rf files


#!/bin/bash

for file in $(ls)
do
if [ ! -s $file ]
then
rm -i $file
fi
done




目录可以自己任意输,所以写了下面程序rm_empty_file2.sh。没有参数 就是当前目录;输入参数目录就是参数目录;错误目录当然会有错误

#!/bin/bash
if [ $# -eq 1 ]
then
dir=$1 # $1为 ./xx.sh 后面的第一个参数
else
dir=""
fi
# 目录错误?
for file in $(ls $dir)
do
filetmp=${dir}${file} #字符串连接
#       echo $filetmp
if [ ! -s $filetmp ]
then
rm -i $filetmp
fi
done




参考:

bash shell命令行选项与修传入参数处理: /article/1281383.html

linux shell 编程 删除空文件 : http://blog.163.com/gaga_blog/blog/static/214068175201211129020225/

2 查找目录下 大于100字节的文件,显示文件名和其大小

利用ls -l 命令 和 awk命令

#!/bin/bash
# 用逗号隔开文件名 和 文件大小
for files in `ls -l | awk '$5>100 {print $9","$5}'`
do
#echo $files
echo $files | awk -F , '{print $1" "$2}'
done




awk命令参考:/article/1313649.html

非常好的十道Linux shell脚本面试题:http://www.2cto.com/os/201309/241532.html

3 设计一个Shell程序,在/userdata目录下建立50个目录,即user1~user50,并设置每个目录的权限,其中其他用户的权限为:读;文件所有者的权限为:读、写、执行;文件所有者所在组的权限为:读、执行。

题目解答:http://www.yjbys.com/bbs/361072.html

Linux下shell脚本判断文件相关属性:/article/6004302.html

test 测试命令

echo $? 可以查看上一条执行命令执行是否成功

这题会有还会有权限问题,因为在根目录下创建文件夹

统计c代码量

查看目录下有多少个.c 文件



进一步编写如下shell脚本 c.count.sh

#!/bin/bash

cfiles=`find . -name "*.c"`
for file in $cfiles
do
echo $file
#cat $file
file_l=`cat $file | wc -l`
echo $file_l
done


在目录下运行



shell算数运算

/article/8271597.html

/article/4130403.html

修改脚本

#!/bin/bash
sum_l=0
cfiles=`find . -name "*.c"`
for file in $cfiles
do
#echo $file
#cat $file
file_l=`cat $file | wc -l`
#echo $file_l
((sum_l=$sum_l+$file_l))
done
echo $sum_l




空行问题

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: