shell学习笔记(续一) 处理用户输入

1.运行带参数的程序

$0表示程序名,$1表示第一个参数,$2表示第二个参数,一次类推,直到第九个参数$9

# vi factorial

#!/bin/shf=1for((i=1;i<=$1;i++))dof=$[ $f * $i]doneecho $f测试:

[root@master test]# ./factorial 5120

注意:如果有多个参数,每个参数必须有个空格,如果一个参数里面带空格,必须用单引号或双引号括起来。

2.读取程序名

编写基于所用的脚本名而执行不同功能的脚本

#vi addem

#!/bin/shname=`basename $0`echo $nameif [ $name = "addem" ]thenecho $[$1+$2]elif [ $name = "mulem" ]thenecho $[ $1 * $2]fi

#cpaddem 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" ]docase "$1" in-a) echo "-a option" ;;-b) echo "-b option" ;;-c) echo "-c option" ;;*) echo "$1 is not an option" ;;esacshiftdone

测试:

[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 linedoecho "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!

只剩下一条路,那就是成功的路。

shell学习笔记(续一) 处理用户输入

相关文章:

你感兴趣的文章:

标签云: