當(dāng)前位置:
首頁 >
Linux基础(6)
發(fā)布時(shí)間:2023/10/11
152
老码农
生活随笔
收集整理的這篇文章主要介紹了
Linux基础(6)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Linux基礎(chǔ)(六)
shell腳本中的三大循環(huán)和函數(shù)知識點(diǎn)
一、流程控制之if結(jié)構(gòu)
1.簡單的if實(shí)例:
#!/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
執(zhí)行效果:
2.向腳本傳遞參數(shù)
eg:
#3.sh
echo $0
echo $1
echo $2
echo $3
echo ${11}
echo '$$' $$
echo '$*' $*
echo '$@' $@
echo '$#' $#
echo '$?' $?
測試結(jié)果:
[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
$#
$? 0
二.循環(huán)結(jié)構(gòu)之while
while (條件)
do
動(dòng)作
done
需要無限循環(huán)時(shí)我們會選擇while :
寫個(gè)腳本 讓用戶輸入,輸入數(shù)字通過,輸出錯(cuò)誤重新輸入
#!/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 == '' ]
then
echo 'login sucessful'
login=1
fi
done
運(yùn)行及查看結(jié)果:
[root@localhost ~]# ./4.sh
please input your name: egon
please input your password: 123
login sucessful
[root@localhost gandong]#
三、循環(huán)結(jié)構(gòu)之for
shell格式的for
for i in {1..10}
do
echo $i
done
[root@localhost ~]# ./5.sh
1
2
3
4
5
6
7
8
9
10
應(yīng)用循環(huán)和條件判斷寫的一個(gè)實(shí)例:
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 '========================================================' ~
四、函數(shù)知識點(diǎn)
交互shell中的函數(shù)
eg:
vim 7.sh
function abc() {
echo 'aaa';echo 'bbbb';
}
abc
運(yùn)行結(jié)果:
[root@localhost ~]# vim 7.sh
[root@localhost ~]# ./7.sh
aaa
bbbb
總結(jié)
以上是生活随笔為你收集整理的Linux基础(6)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于mybatis缓存配置讲解
- 下一篇: Redis的安装与使用