Linux学习-shell脚本编程基础之处理用户输入
来源:互联网 发布:战斗力获取数据超时 编辑:程序博客网 时间:2024/05/16 15:46
1.运行带参数的程序
$0表示程序名,$1表示第一个参数,$2表示第二个参数,一次类推,直到第九个参数$9
# vi factorial
#!/bin/shf=1for((i=1;i<=$1;i++))do f=$[ $f * $i]doneecho $f测试:
[root@master test]# ./factorial 5120
注意:如果有多个参数,每个参数必须有个空格,如果一个参数里面带空格,必须用单引号或双引号括起来。
2.读取程序名
编写基于所用的脚本名而执行不同功能的脚本
# vi addem
#!/bin/shname=`basename $0`echo $nameif [ $name = "addem" ]then echo $[$1+$2]elif [ $name = "mulem" ]then echo $[ $1 * $2]fi
# cp addem mulem
测试:
[root@master test]# sh addem 3 47[root@master test]# sh mulem 33 399
3.参数计数
可以通过 $# 来统计参数的个数。
可以通过 ${!#} 来获得最后一个命令行参数变量,或者是params=$#,然后用$params 获得也可以。
4.获得所有数据
$*和$@变量提供了对所有参数的快速访问。
[root@master test]# vi test11#!/bin/sh# testing $* and $@echo "Using the \$* method:$*"echo "Using the \$@ method:$@"测试:[root@master test]# ./test11 rich jjds fds qaa dsddUsing the $* method:rich jjds fds qaa dsddUsing the $@ method:rich jjds fds qaa dsdd
$*:存储的数据相当于单个单词;
$@:存储的数据相当于多个独立的单词。
5.shift移动变量
使用shift可以把参数都向前移动一位,$1会被移调,最后$#的大小会减掉1
使用shift 2 表示一次移动两位
判断带入的参数是否不为空:if [ -n $1 ] 表示判断$1是否为空
6.查找选项
# vi test12
#!/bin/sh# extracting command line options as parameterswhile [ -n "$1" ]do case "$1" in -a) echo "-a option" ;; -b) echo "-b option" ;; -c) echo "-c option" ;; *) echo "$1 is not an option" ;; esac shiftdone
测试:
[root@master test]# ./test12 -a-a option[root@master test]# ./test12 cc is not an option[root@master test]#
7.getopt命令和getopts命令
8.获得用户输入
# vi test13
#!/bin/shecho "please enter you name:"read nameecho "hello $name ,where come to here"测试:[root@master test]# ./test13please enter you name:hahahello haha ,where come to here
可以在read后面直接跟指定提示符:
read –p "please entry you age:" age
还可以使用-t设置计时器
read –t 5 –p "please entry you age:" age
其它参数:
-s隐式方式读取,数据会被显示,只是read命令会将文本颜色设置成跟背景色一样;
9.从文件中读取数据
# vi test15
#!/bin/shcount=1cat test | while read linedo echo "Line $count: $line" count=$[$count + 1]doneecho "finish file!"测试
[root@master test]# ./test15Line 1: #!/bin/shLine 2: if dateLine 3: thenLine 4: echo "it worked!"Line 5: fiLine 6: echo "this is a test file"Line 7: echo "this is a test file"finish file!
1 0
- Linux学习-shell脚本编程基础之处理用户输入
- [shell脚本学习]处理用户输入
- linux shell 学习之第13章 处理用户输入
- Shell脚本学习笔记-用户输入处理
- shell 脚本编程学习(二) 变量,用户输入,参数
- linux shell 处理用户输入
- Linux命令行与shell编程笔记-13处理用户输入
- linux之基础shell脚本编程4 字符串操作,变量赋值,配置用户环境
- linux学习之shell脚本 ------- 基础
- Shell脚本基础3-获取用户输入
- linux之基础shell脚本编程1 基础变量赋值
- Linux shell 脚本编程基础
- Linux Shell脚本编程基础
- Linux Shell脚本编程基础
- Linux Shell脚本编程基础
- shell脚本编程之基础
- Bash shell编程<六>:处理用户输入
- linux学习之shell脚本 ------- 输入与输出
- extern数组与extern指针
- 日志框架Log4j详解
- PyQt5 GUI图标的设置
- 开源项目WilliamChart的学习笔记1_demo的学习
- zoj 2334 Monkey King/左偏树+并查集
- Linux学习-shell脚本编程基础之处理用户输入
- [G+smo]Interpolation and look up
- 【php】5、学生管理系统-管理员欢迎界面
- Install Robot Framework on Linux Fedora20 or ubuntu /on Mac /on windows
- NTP-Windows 2008和win7下开启网络对时方法
- 欢迎使用CSDN-markdown编辑器
- 疯狂Java之学习笔记(25)-------------修饰符
- 你应该知道的浮点数基础知识
- 蛇形矩阵