openKylin论坛

 找回密码

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>
在脚本中提供帮助是一种很好的编程习惯,可以方便其他用户(和自己)使用和理解脚本。
楼主
发表于 2013-5-7 14:24:01
回复

使用道具 举报

openKylin

GMT+8, 2024-5-2 14:51 , Processed in 0.019350 second(s), 17 queries , Gzip On.

Copyright ©2022 openKylin. All Rights Reserved .

ICP No. 15002470-12 Tianjin

快速回复 返回顶部 返回列表