Linux 指令碼編寫基礎(四)

來源:互聯網
上載者:User

4)函數

如果您寫了一些稍微複雜一些的程式,您就會發現在程式中可能在幾個地方使用了相同的代碼,並且您也會發現,如果我們使用了函數,會方便很多。一個函數是這個樣子的:

functionname()

{

# inside the body $1 is the first argument given to the function

# $2 the second ...

body

}

您需要在每個程式的開始對函數進行聲明。

下面是一個叫做xtitlebar的指令碼,使用這個指令碼您可以改變終端視窗的名稱。

這裡使用了一個叫做help的函數。正如您可以看到的那樣,這個定義的函數被使用了兩次。

#!/bin/sh

# vim: set sw=4 ts=4 et:

help()

{

cat <

xtitlebar -- change the name of an xterm, gnome-terminal or kde konsole

USAGE: xtitlebar [-h] "string_for_titelbar"

OPTIONS: -h help text

EXAMPLE: xtitlebar "cvs"

HELP

exit 0

}

# in case of error or if -h is given we call the function help:

[ -z "$1" ] && help

[ "$1" = "-h" ] && help

# send the escape sequence to change the xterm titelbar:

echo -e "33]0;$107"

#

在指令碼中提供協助是一種很好的編程習慣,這樣方便其他使用者(和您)使用和理解指令碼。

命令列參數

我們已經見過$* 和 $1, $2 ... $9 等特殊變數,這些特殊變數包含了使用者從命令列輸入的參數。迄今為止,我們僅僅瞭解了一些簡單的命令列文法(比如一些強制性的參數和查看協助的-h選項)。但是在編寫更複雜的程式時,您可能會發現您需要更多的自訂的選項。通常的慣例是在所有可選的參數之前加一個減號,後面再加上參數值 (比如檔案名稱)。有好多方法可以實現對輸入參數的分析,但是下面的使用case運算式的例子無遺是一個不錯的方法。

#!/bin/sh

help()

{

cat <

This is a generic command line parser demo.

USAGE EXAMPLE: cmdparser -l hello -f -- -somefile1 somefile2

HELP

exit 0

}

while [ -n "$1" ]; do

case $1 in

-h) help;shift 1;; # function help is called

-f) opt_f=1;shift 1;; # variable opt_f is set

-l) opt_l=$2;shift 2;; # -l takes an argument -> shift by 2

--) shift;break;; # end of options

-*) echo "error: no such option $1. -h for help";exit 1;;

*) break;;

esac

done

echo "opt_f is $opt_f"

echo "opt_l is $opt_l"

echo "first arg is $1"

echo "2nd arg is $2"

您可以這樣運行該指令碼:

cmdparser -l hello -f -- -somefile1 somefile2

返回的結果是:

opt_f is 1

opt_l is hello

first arg is -somefile1

2nd arg is somefile2

這個指令碼是如何工作的呢?指令碼首先在所有輸入命令列參數中進行迴圈,將輸入參數與case運算式進行比較,如果匹配則設定一個變數並且移除該參數。根據unix系統的慣例,首先輸入的應該是包含減號的參數.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.