[shell]shell脚本-求和&参数处理等
2017-05-19 14:23
561 查看
1,计算100以内数字的和
函数传递参数
2,计算2个数的和
3.查询txl的案例
4,参数处理
可以手工处理
判断字符串是否为空:
也可以借助getopts
现在就可以使用:
./test.sh -a arg -b -c
或
./test.sh -a arg -bc
来加载了。
应该说绝大多数脚本使用该函数就可以了,如果需要支持长选项以及可选参数,那么就需要使用getopt
#!/bin/bash sum=0 for i in $(seq 100);do sum=$[$i+$sum] done echo $sum
函数传递参数
#!/bin/bash # author:菜鸟教程 # url:www.runoob.com funWithParam(){ echo "第一个参数为 $1 !" echo "第二个参数为 $2 !" echo "第十个参数为 $10 !" echo "第十个参数为 ${10} !" echo "第十一个参数为 ${11} !" echo "参数总数有 $# 个!" echo "作为一个字符串输出所有参数 $* !" } funWithParam 1 2 3 4 5 6 7 8 9 34 73
2,计算2个数的和
$ cat sum.sh #!/bin/bash funWithReturn() { return $(( $1+$2 )) } funWithReturn $@ ret=$? echo "sum = $ret"
3.查询txl的案例
#!/bin/bash print_help() { echo "Usage: $0 args1" exit 1 } txl_add(){ echo "增加通讯录" } txl_delete(){ echo "删除通讯录" } txl_update(){ echo "更新讯录" } txl_cha(){ echo "查询通讯录" } main(){ while :;do case $1 in 1) txl_add ;; 2) txl_delete ;; 3) txl_update ;; 4) txl_delete ;; *) print_help ;; esac done } main
4,参数处理
可以手工处理
判断变量 read -p "input a word :" word if [ ! -n "$word" ] ;then echo "you have not input a word!" else echo "the word you input is $word" fi 判断输入参数 #!/bin/bash if [ ! -n "$1" ] ;then echo "you have not input a word!" else echo "the word you input is $1" fi
判断字符串是否为空:
$ [ -z $String ] #为空,则视为正确 $ echo $? 0
$ if [ ! -z $String ];do xxx ;done如果 String="" 或者String未定义,则都返回0
也可以借助getopts
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->#test.sh #!/bin/bash while getopts "a:bc" arg #选项后面的冒号表示该选项需要参数 do case $arg in a) echo "a's arg:$OPTARG" #参数存在$OPTARG中 ;; b) echo "b" ;; c) echo "c" ;; ?) #当有不认识的选项的时候arg为? echo "unkonw argument" exit 1 ;; esac done
现在就可以使用:
./test.sh -a arg -b -c
或
./test.sh -a arg -bc
来加载了。
应该说绝大多数脚本使用该函数就可以了,如果需要支持长选项以及可选参数,那么就需要使用getopt
#! /bin/sh while getopts a:bc arg do case $arg in "a") echo "a: $OPTARG ($OPTIND)" ;; "b") echo "bb ($OPTIND)" ;; "c") echo "ccc ($OPTIND)" ;; ?) echo "unkonw argument ($OPTIND)" ;; esac done
列子1: if [ -n "$1" ] #如果$1即参数1不为空,又即存在参数1 # 被测试的变量被双引号引起 then echo "Parameter #1 is $1" # 使用引号来使#被转义 fi if [ -z "$1" ] #如果$1即参数1为空(零),又即不存在参数1 then fi
相关文章推荐
- 使用getopts处理Shell脚本参数 (转)
- shell脚本中用getopts处理用户输入选项和参数
- shell脚本编程实例--进度条,求和&平均值,斐波那契,改变字符串大小顺序
- shell脚本中如何获取命令的参数(2) ----处理命令参数
- 【Shell脚本】逐行处理文本文件 && 空格变换行
- Shell脚本:命令选项参数处理
- getopts 处理shell脚本参数
- shell脚本选项参数处理学习getopts|getopt
- Linux命令参数处理 shell脚本函数getopts
- 使用getopts处理Shell脚本参数
- shell中通过${}处理脚本参数
- shell脚本处理长参数的模板
- 脚本乐园 Shell中命令行选项和参数的处理
- shell学习 - 处理脚本的多参数输入
- shell脚本处理长参数的模板
- Shell脚本中参数处理方法
- 使用getopt处理shell脚本的参数
- 使用getopts处理Shell脚本参数
- 脚本乐园 Shell中命令行选项和参数的处理
- 使用getopt处理shell脚本的参数 推荐