Linux shell 基础(六),自己慢慢一步步学
来源:互联网 发布:新版淘宝vip等级没了 编辑:程序博客网 时间:2024/04/29 17:11
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系统的惯例,首先输入的应该是包含减号的参数。
- Linux shell 基础(六),自己慢慢一步步学
- Linux shell 基础(一),自己慢慢一步步学
- Linux shell 基础(二),自己慢慢一步步学
- Linux shell 基础(三),自己慢慢一步步学
- Linux shell 基础(四),自己慢慢一步步学
- Linux shell 基础(五),自己慢慢一步步学
- Linux shell 基础(七),自己慢慢一步步学
- Linux shell 基础(八),自己慢慢一步步学
- 自己慢慢学Linux积攒的笔记
- 如和一步步学编程,慢慢提升
- Linux shell入门基础(六)
- linux命令大全(自己慢慢看)
- shell基础(六)
- 一步步学汇编(六)内存寻址方式
- 一步步学汇编(六)内存寻址方式
- Linux之ubuntu学习笔记(六):shell基础
- 详细介绍Linux shell脚本基础学习(六)
- linux shell基础六之指令
- 电脑清灰过后,CPU温度下降,显卡温度却上升了
- 一个问题引发的思考
- Image与Canvas相互转换
- 收罗CSS布局居中的N中方法(水平和垂直)
- 《c++ Primer(第四版)》习题 9.35
- Linux shell 基础(六),自己慢慢一步步学
- tomcat的Context配置
- linux下关掉占用某端口的进程
- leetcode第一刷_Triangle
- 《c++ Primer(第四版)》习题 9.36
- Linux shell 基础(七),自己慢慢一步步学
- Flex读取txt文件中的内容(三)
- standard.jar和jstl.jar的下载地址
- 《c++ Primer(第四版)》习题 9.38