专注各种脚本编程
Baidu
加入收藏夹
本站内容有下面分类知识,欢迎您的到来^_^
shell相关:指令篇 基础篇 脚本欣赏 编程实例 shell问问 shell视频教程 技巧篇 水平测试 E文资料 vi编辑器 高级Bash脚本编程指南
其他:mysql perl c语言 oracle
当前位置:| 主页>shell脚本欣赏>

shell脚本显示文件的最后5行数据

百度收藏 QQ搜藏

原文:http://bash.cyberciti.biz/academic/display-last-lines-of-file/
我们先让用户自己输入文件名(最好是文本文件啦,不然会有一些显示乱码),检查文件是否存在,再利用shell命令里的tail命令显示该文件的最后5行数据。

Shell Script代码如下:

#!/bin/bash
# get filename
echo -n "Enter File Name : "
read fileName
 
# make sure file exits for reading
if [ ! -f $fileName ]; then
  echo "Filename $fileName does not exists"
  exit 1
fi
 
# display last five lines of the file using tail command
tail -5 $fileName

当然我们也可以使用"命令行参数(Command Line Argument)"来编写有这种功能的shell脚本,代码如下:

#!/bin/bash
# get filename
fileName="$1"
# make sure command line arg provided
if [ -z $1 ]; then
	echo "Syntax: $(basename $0) filename"
	exit 1
fi
# make sure file exits for reading
if [ ! -f $fileName ]; then
  echo "Filename $fileName does not exists"
  exit 1
fi
# ok display last five lines of the file using tail command
tail -5 $fileName
上一篇:shell脚本 在Linux/Unix系统里搜索所有有可写权限的文件和文件夹 下一篇:shell程序循环显示1到10的数字

power by soyo123 2007-2008