时间:2024-04-17 09:06:59 来源: 人气:
今天这个例子是 用来验证用户输入的参数的合法性的,程序并不复杂,如下所示:
#!/bin/sh
# validAlphaNum - Ensures that input consists only of alphabetical
# and numeric characters.
validAlphaNum()
{
# Validate arg: returns 0 if all upper+lower+digits, 1 otherwise
# Remove all unacceptable chars
compressed="$(echo $1 | sed -e 's/[^[:alnum:]]//g')"
if [ "$compressed" != "$input" ] ; then
return 1
else
return 0
fi
}
# Sample usage of this function in a script
echo -n "Enter input: "
read input
if ! validAlphaNum "$input" ; then #// 这个有点巧妙,就是如果函数的返回值为1的话,则执行
echo "Your input must consist of only letters and numbers." >&2
exit 1
else
echo "Input is valid."
fi
exit 0
就像上面所说这脚本流程和思路还是很简明的,就是讲你的输入用sed过滤后于原输入相比较,不相等则输入不合法。
值得注意的地方有
1) sed -e 's/[^ [:alnum:]]//g' ([:alnum:]是 大小写字母及数字的意思,这里sed的作用是将非大小写字母及数字过滤掉。
2) if ! validAlphaNum "$input" $input作为 函数的参数被调用,注意这里加了引号。
用来检测输入的选项$1是否在PATH中的shell脚本
今天无意中发现一本挺有意思的shell编程的书,是e文的,内容是101个shell案例,坚持明天看一个,写点心得。下面是例子001:#!/bin/sh#inpath-Verifiesthataspecif
linux shell实现转换输入日期的格式
对于用户输入日期的合法性检验,是个很重要的问题,这个例子是简单得取得用户输入的日期,并转换为相应的格式,但不完美,原因请看后文。#!/bin/s
自动化下载并检测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