码迷,mamicode.com
首页 > 系统相关 > 详细

Linux基础(6)

时间:2017-04-09 16:24:42      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:应用   脚本   效果   lin   amp   open   welcome   格式   break   

Linux基础(六)

shell脚本中的三大循环和函数知识点

一、流程控制之if结构

1.简单的if实例:

技术分享
#!/bin/bash
var=/etc/init.d
#var=‘/dev/sda‘
if [ -d $var ]
    then
        echo "$var is directory"
elif [ -b $var ]
    then
        echo "$var is block"
elif [ -f $var ]
    then
        echo "$var is regular file"
else
        echo unknow
fi
View Code

执行效果:

技术分享

2.向脚本传递参数

eg:

技术分享
#3.sh
echo $0
echo $1
echo $2
echo $3
echo ${11}
echo $$ $$
echo $* $*
echo $@ $@
echo $# $#
echo $? $?
View Code

测试结果:

技术分享
[root@localhost ~]# ./3.sh 1 2 3 4 5 6 7 8 9 10
./3.sh
1
2
3

$$ 8755
$* 1 2 3 4 5 6 7 8 9 10
$@ 1 2 3 4 5 6 7 8 9 10
$# 10
$? 0
View Code

二.循环结构之while

while (条件)

do
动作
done

需要无限循环时我们会选择while :
写个脚本 让用户输入,输入数字通过,输出错误重新输入

技术分享
#!/bin/bash
login=0
while [ $login != 1 ]
do
    read -p please input your name:  name
    read -p please input your password:  pwd
    if [ $name == egon ] && [ $pwd == 123 ]
        then
            echo login sucessful
            login=1
    fi
done
View Code

运行及查看结果:

技术分享
[root@localhost ~]# ./4.sh
please input your name: egon
please input your password: 123
login sucessful
[root@localhost gandong]# 
View Code

三、循环结构之for

shell格式的for

技术分享
for i in {1..10}
do
echo $i
done
View Code
技术分享
[root@localhost ~]# ./5.sh 
1
2
3
4
5
6
7
8
9
10
View Code

应用循环和条件判断写的一个实例:

技术分享
vim 6.sh

while :
do

    read -p please input your name:  name
    read -p please input your password:  psd
    if [-z $name ] || [-z $psd ]
        then
            continue
    fi
    if [ $name = alex  -a $psd = alex3714 ]
        then
            echo login successful ,welcome da SB
            while :
            do
                read -p please input your cmd:  cmd
                if [ $cmd = quit ]
                    then
                        break
                fi
                $cmd
            done
    else      
        echo username or password is error
    fi
done
    
echo ========================================================
    
~                                                   
View Code

四、函数知识点

交互shell中的函数

eg:

技术分享
vim 7.sh
function abc() {
 echo aaa;echo bbbb;
 }
abc
View Code

运行结果:

技术分享
[root@localhost ~]# vim 7.sh
[root@localhost ~]# ./7.sh
aaa
bbbb
View Code

 

Linux基础(6)

标签:应用   脚本   效果   lin   amp   open   welcome   格式   break   

原文地址:http://www.cnblogs.com/haishiniu123/p/6685075.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!