1. 擷取使用者輸入
.
參數是輸入提示, 輸入值的正確檢查的Regex, 輸入預設值.
返
回的是使用者的正確輸入.
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/