脚本练习
达到的效果 ./output.sh 5 file.txt 输出指定文件第5行
./output 5-10 file.txt 输出指定文件第5-10行
#!/bin/bash ###read the argument to output the file content. if [ -n $1 ] && ! [[ $1 =~ [a-zA-Z] ]] && [ -f $2 ];then #判断行的参数是否存在且为数字,打开的文件是否存在 if [[ $1 =~ [0-9]+-[0-9]+ ]];then #判断行参数是否符合 num-num的格式 line_start=$[ `echo $1|cut -d\- -f1` + 1 ] #将参数中的首行赋给line_start line_end=`echo $1|cut -d\- -f2` #将参数中的末行赋给line_end if [[ $line_end -gt $line_start ]];then #判断行尾大于行首且行尾不大于文件总行 if [[ $line_end -le `cat $2|wc -l` ]];then cat $2|head -$line_end|tail -$line_start else echo "The line_end is out of file range." exit 2 fi else echo "The line_end can‘t greater than the line_start. " exit 3 fi else if [[ $1 -le `cat $2|wc -l` ]];then #判断指定行是否小于等于文件的总行数 cat $2|head -$1|tail -1 else echo "The line is out of the file range" exit 4 fi fi else echo -e "Argument Error! \nThe usage is . /output line_start filename or ./output line_start-line_end filename\nExplame: ./output 5-10 /etc/passwd" exit 1 fi
原文地址:http://dannniswu.blog.51cto.com/9846650/1844714