1. 获取用户输入 .
参数是输入提示, 输入值的正确检查的正则表达式, 输入默认值.
返 回的是用户的正确输入.
function get_input()
{
PROMPT=$1
REGEX=$2
DEFAULT=$3
if [ "X${DEFAULT}" = "X" ]; then
echo "${PROMPT}" 1>&2
read INPUT
CHK_RESULT=`echo "${INPUT}" | egrep "^${REGEX}$"`
while [ "X${CHK_RESULT}" = "X" ]; do
echo "Format error. Please input again:" 1>&2
read INPUT
CHK_RESULT=`echo "${INPUT}" | egrep "^${REGEX}$"`
done
echo "${INPUT}"
else
echo "${PROMPT} [${DEFAULT}]" 1>&2
read INPUT
if [ "X${INPUT}" = "X" ]; then
echo "${DEFAULT}"
return 0
fi
CHK_RESULT=`echo "${INPUT}" | egrep "^${REGEX}$"`
while [ "X${CHK_RESULT}" = "X" ]; do
echo "Format error. Please input again: [${DEFAULT}]" 1>&2
read INPUT
if [ "X${INPUT}" = "X" ]; then
echo "${DEFAULT}"
return 0
fi
CHK_RESULT=`echo "${INPUT}" | egrep "^${REGEX}$"`
done
echo "${INPUT}"
fi
}
例子:
RE_IP='((([1-9]?[0-9])|(1[0-9]{2})|(2([0-4][0-9]|5[0-5])))/.){3}(([1-9]?[0-9])|(1[0-9]{2})|(2([0-4][0-9]|5[0-5])))'
CURR_IP=`get_input "Please input current IP:" "${RE_IP}" "127.0.0.1"`
CURR_IP就是用户输入的正确值, 如果直接回车的话, 就是默认值"127.0.0.1".
函数是利用 错误输出通道(2)来打印提示串, 默认值(如果有)会出现在提示后的[]里. 利用标准输出通道(1)来返回函数的处理结果. 函数还拥有值格式错误重输机制.
2. 当前用户检查
function check_user()
{
EXPECT_USER=$1
USER="`id -un`"
if [ "${USER}" != "${EXPECT_USER}" ]; then
echo "Current user is [${USER}]."
echo "You must run this shell with user [${EXPECT_USER}]."
return 1
fi
}
3. 获取指定关键字的进程的pid
function get_pid()
{
PROC_SIGN=$1
PROC_PID=`ps axwwo '%p %a' |grep ${PROC_SIGN} |grep -v '^ *[0-9]/+ grep ' |awk '{print $1}'`
echo ${PROC_PID}
}
转自:http://blog.163.com/panfeng_pf/blog/static/11196085420093205644479/