《Linux命令行与shell脚本编程大全》 第十三章 学习笔记

第一部分:Linux命令行《Linux命令行与shell脚本编程大全》 第一章:初识Linux shell《Linux命令行与shell脚本编程大全》 第二章:走进shell《Linux命令行与shell脚本编程大全》 第三章:基本的bash shell命令《Linux命令行与shell脚本编程大全》 第四章:更多的bash shell命令《Linux命令行与shell脚本编程大全》 第五章:使用Linux环境变量《Linux命令行与shell脚本编程大全》 第六章:理解Linux文件权限《Linux命令行与shell脚本编程大全》 第七章:管理文件系统《Linux命令行与shell脚本编程大全》 第八章:安装软件程序《Linux命令行与shell脚本编程大全》 第九章:使用编辑器第二部分:shell脚本编程基础《Linux命令行与shell脚本编程大全》 第十章:构建基本脚本《Linux命令行与shell脚本编程大全》 第十一章:使用结构化命令《Linux命令行与shell脚本编程大全》 第十二章:更多的结构化命令《Linux命令行与shell脚本编程大全》 第十三章:处理用户输入《Linux命令行与shell脚本编程大全》 第十四章:呈现数据《Linux命令行与shell脚本编程大全》 第十五章:控制脚本第三部分:高级shell编程《Linux命令行与shell脚本编程大全》 第十六章:创建函数《Linux命令行与shell脚本编程大全》 第十七章:图形化桌面上的脚本编程《Linux命令行与shell脚本编程大全》 第十八章:初识sed和gawk《Linux命令行与shell脚本编程大全》 第十九章:正则表达式《Linux命令行与shell脚本编程大全》 第二十章:sed进阶《Linux命令行与shell脚本编程大全》 第二十一章:gawk进阶《Linux命令行与shell脚本编程大全》 第二十二章:使用其他shell第四部分:高级shell脚本编程主题《Linux命令行与shell脚本编程大全》 第二十三章:使用数据库《Linux命令行与shell脚本编程大全》 第二十四章:使用Web《Linux命令行与shell脚本编程大全》 第二十五章:使用E-mail《Linux命令行与shell脚本编程大全》 第二十六章:编写脚本实用工具《Linux命令行与shell脚本编程大全》 第二十七章:shell脚本编程进阶

第十三章:处理用户输入命令行参数读取参数bash shell会将一些称为位置参数(positional parameter)的特殊变量分配给命令行输入的所有参数甚至包括程序名$0:程序名(程序的绝对路径),可以对$0使用basename函数(basename $0),它只返回程序名$i(9>i>0):第i个参数如果需要的参数多于9个,那么只需${10},这样既可如果脚本需要参数,但是执行的时候并没有输入参数,执行的时候则会得到错误

if [ -n "$1" ]……

应该先检查是否有参数,然后再做处理特殊参数变量$#:参数数量${!#}:最后一个参数。花括号({})中不允许使用美元符号($),这里使用感叹号(!)

所以下面的代码是错误的

#!/bin/bashecho We have "$#" "parameter(s)"echo The last parameter is "${$#}" # wrong wayecho The last parameter is "${!#}" # right way

执行结果:

$ param_test 1 1 1 5We have 4 parameter(s)The last parameter is 1535The last parameter is 5

注意:当命令行没有任何参数时,$#返回0,而${!#}返回函数名提取命令行上的所有参数$*:将命令行上提供的所有参数当做1个单词保存$@:所有参数的集合

#!/bin/bashecho "\$* and \$@ test"echo "\$* is:"$* #这里两个输出结果是一样的echo "\$@ is:"$@ #count=0for var in "$*"do    count=$[$count+1]    echo "$count:"$vardoneecho "\$* done."count=0for var in "$@"do    count=$[$count+1]    echo "$count:"$vardoneecho "\$@ done."

输出结果:

$* and $@ test$* is:a b c$@ is:a b c1:a b c$* done.1:a2:b3:c$@ done.

移动数据shift

将每个变量的位置都提前一个,$0不变,$1被移除。

count=1while [ -n "$1" ]do    echo "Paramter #$count=$1"    count=$[$count + 1]    shiftdone

注意:当参数被移除之后,无法恢复。

处理选项

while [-n $1 ]do    case "$1" in    -a) echo "Found the -a option" ;;    -b) echo "Found the -b option" ;;    *) echo "$1 is not a option" ;;    esac    shiftdone

分离参数和选项

Linux利用双破折线(–)表明选项结束。

#!/bin/bashwhile [ -n "$1" ]do    case "$1" in    -a) echo "Found option a";;    -b) echo "Found option b";;    --) shift         break;;#跳出while,而不是case    *) echo "$1 not a option";;    esac    shiftdonefor p in $@do    echo "$p is a param ."done

人生才会更有意义。如果没有梦想,那就托做庸人。

《Linux命令行与shell脚本编程大全》 第十三章 学习笔记

相关文章:

你感兴趣的文章:

标签云: