您的位置:首页 > 运维架构 > Shell

Linux学习-shell脚本编程基础之处理用户输入

2015-04-28 20:18 1386 查看
1.运行带参数的程序

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

# vi factorial

#!/bin/sh
f=1
for((i=1;i<=$1;i++))
do
        f=$[ $f * $i]
done
echo $f
测试:

[root@master test]# ./factorial 5
120


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

2.读取程序名

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

# vi addem

#!/bin/sh
name=`basename $0`
echo $name
if [ $name = "addem" ]
then
        echo $[$1+$2]
elif [ $name = "mulem" ]
then
        echo $[ $1 * $2]
fi

# cp addem mulem

测试:

[root@master test]# sh addem 3 4
7
[root@master test]# sh mulem 33 3
99

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 dsdd
Using the $* method:rich jjds fds qaa dsdd
Using 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 parameters
while [ -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
        shift
done

测试:

[root@master test]# ./test12 -a
-a option
[root@master test]# ./test12 c
c is not an option
[root@master test]#

7.getopt命令和getopts命令



8.获得用户输入

# vi test13

#!/bin/sh
echo "please enter you name:"
read name
echo "hello $name ,where come to here"
测试:
[root@master test]# ./test13
please enter you name:
haha
hello 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/sh
count=1
cat test | while read line
do
        echo "Line $count: $line"
        count=$[$count + 1]
done
echo "finish file!"
测试

[root@master test]# ./test15
Line 1: #!/bin/sh
Line 2: if date
Line 3: then
Line 4: echo "it worked!"
Line 5: fi
Line 6: echo "this is a test file"
Line 7: echo "this is a test file"
finish file!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: