openKylin论坛

标题: shell 5 [打印本页]

作者: liuxing    时间: 2013-5-7 14:24
标题: shell 5
== Shell里的函数  ==

如果你写过比较复杂的脚本,就会发现可能在几个地方使用了相同的代码,这时如果用上函数,会方便很多。函数的大致样子如下:

functionname()
{
# inside the body $1 is the first argument given to the function
# $2 the second ...
body
}



函数没有必要声明。只要在执行之前出现定义就行

下面是一个名为xtitlebar的脚本,它可以改变终端窗口的名称。这里使用了一个名为help的函数,该函数在脚本中使用了两次:
<pre>#!/bin/bash

help()
{
cat &lt;&lt; HELP
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" ] &amp;&amp; help
[ "$1" = "-h" ] &amp;&amp; help
# send the escape sequence to change the xterm titelbar:
echo -e "\033]0;$1\007"
# </pre>
在脚本中提供帮助是一种很好的编程习惯,可以方便其他用户(和自己)使用和理解脚本。





欢迎光临 openKylin论坛 (https://forum.openkylin.top/) Powered by Discuz! X3.3