时间:2024-03-11 16:55:15 来源: 人气:
对于用户输入日期的合法性检验,是个很重要的问题,这个例子是简单得取得用户输入的日期,并转换为相应的格式,但不完美,原因请看后文。
#!/bin/sh
# normdate -- Normalizes month field in date specification
# to three letters, first letter capitalized. A helper
# function for Script #7, valid-date. Exits w/ zero if no error.
monthnoToName()
{
# Sets the variable 'month' to the appropriate value
case $1 in
1 ) month="Jan" ;; 2 ) month="Feb" ;;
3 ) month="Mar" ;; 4 ) month="Apr" ;;
5 ) month="May" ;; 6 ) month="Jun" ;;
7 ) month="Jul" ;; 8 ) month="Aug" ;;
9 ) month="Sep" ;; 10) month="Oct" ;;
11) month="Nov" ;; 12) month="Dec" ;;
* ) echo "$0: Unknown numeric month value $1" >&2; exit 1
esac
return 0
}
## Begin main script
if [ $# -ne 3 ] ; then
echo "Usage: $0 month day year" >&2
echo "Typical input formats are August 3 1962 and 8 3 2002" >&2
exit 1
fi
if [ $3 -lt 99 ] ; then
echo "$0: expected four-digit year value." >&2; exit 1
fi
if [ -z $(echo $1|sed 's/[[:digit:]]//g') ]; then
monthnoToName $1
else
# Normalize to first three letters, first upper, rest lowercase
month="$(echo $1|cut -c1|tr '[:lower:]' '[:upper:]')"
month="$month$(echo $1|cut -c2-3 | tr '[:upper:]' '[:lower:]')"
fi
echo $month $2 $3
exit 0
脚本分析:
1) 定义了函数monthnoToName(),用来转换用户输入的数字月份
2)首先判断参数的个数是否为3个,其次判断年份,接着是转换月份格式。
3)if [ -z $(echo $1|sed 's/[[:digit:]]//g') ]; 这句话有点意思,是如果$1被执行sed替换的话,即$1中存在数字
则执行函数monthnoToName(),来转换数字月份。
4)month="$(echo $1|cut -c1|tr '[:lower:]' '[:upper:]')"
month="$month$(echo $1|cut -c2-3 | tr '[:upper:]' '[:lower:]')"
将输入的字符月份转换为标准格式。
5)这个脚本最大的缺陷是虽然将日期的格式转换了,但不能检测过滤不存在的日期。
自动化下载并检测ftp文件备份的shell脚本
实现代码:#!/bin/bash#ftime0=$(ll/root/hbshell/down.txt|awk'{print$7}')#ftime1=$(ll/root/hbshell/down.txt|awk'{print$7}')touch/root/hbshell/down.txtwhile:doif[[/root/hbshell/down.txt-nt/root/hbsh
一个监控网卡流量的shell脚本
实现代码:#!/bin/basheth_in_old=$(ifconfigeth0|grep"RXbytes"|sed's/RXbytes://'|awk'{print$1}')eth_out_old=$(ifconfigeth0|grep"RXbytes"|sed's/.*TXbytes://'|awk'{print$1}')sleep1eth_in_new=$(ifconf
linux shell实现求一个多维数组中的最大和最小值
同事发了一道shell题,是求一个多维数组中的最大和最小值如文件99file:335523569923423454565463411435343375433476756333438907766755我的实现之一:#!/bin/bashecho"thefilei