原文: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 |