本节介绍linux shell编程创建函数的方法。
复制代码代码示例:
functionname()
{ # inside the body $1 is the first argument given to the function # $2 the second ... body }
您需要在每个程序的开始对函数进行声明。
复制代码代码示例:
#!/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" # 在脚本中提供帮助是一种很好的编程习惯,这样方便其他用户(和您)使用和理解脚本。
命令行参数
复制代码代码示例:
#!/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
返回结果: |