一些自寫的Linux Shell Function

來源:互聯網
上載者:User

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/

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.