Linux学习_Shell编程2

流程控制

while循环

基本语法

while [ 条件判断式 ]
do
	程序
done

例子:
从命令行输入一个数n,统计从 1+…+ n 的值是多少?

#!/bin/bash

SUM=0
i=0
while [ $i -le $1 ]
do
        SUM=$[$SUM+$i]
        i=$[$i+1]
done
echo $SUM

[root@nyh shell]# chmod 744 testwhile1.sh 
[root@nyh shell]# ./testwhile1.sh 2
3
[root@nyh shell]# ./testwhile1.sh 20
210
[root@nyh shell]# ./testwhile1.sh 10
55

read读取控制台输入

基本语法
read (选项) (参数)
选项:
-p:指定读取值时的提示符;
-t:指定读取值时等待的时间(秒),如果没有在指定的时间内输入,就不再等待了。。
参数
变量:指定读取值的变量名

例子:
案例1:读取控制台输入一个num值

read -p "请输入一个数num" NUM1
echo "输入的num是$NUM1"

[root@nyh shell]# chmod 744 read.sh 
[root@nyh shell]# ./read.sh 
请输入一个数num30
输入的num是30

案例2:读取控制台输入一个num值,在10秒内输入。

read -t 10 -p "请输入一个数num:" NUM1
echo "输入的num是$NUM1"

10秒内如果没输入就会自动结束

函数

函数介绍

shell编程和其它编程语言一样,有系统函数,也可以自定义函数。系统函数中,我们这里就介绍两个。

系统函数

basename基本语法
功能:返回完整路径最后 / 的部分,常用于获取文件名
basename [pathname] [suffix]
basename [string] [suffix](功能描述:basename命令会删掉所有的前缀包括最后一个(‘/’)字符,然后将字符串显示出来。

选项:
suffix为后缀,如果suffix被指定了,basename会将pathname或string中的suffix去掉。

例子:
请返回 /root/hello.txt 的 “hello.txt” 部分

[root@nyh ~]# basename /root/hello.txt
hello.txt
[root@nyh ~]# basename /root/hello.txt .txt
hello

在脚本中也可以这样子用

dirname基本语法
功能:返回完整路径最后 / 的前面的部分,常用于返回路径部分

dirname 文件绝对路径 (功能描述:从给定的包含绝对路径的文件名中去除文件名(非目录的部分),然后返回剩下的路径(目录的部分))

例子:
返回 /root/hello.txt 的 /root

[root@nyh ~]# dirname /root/hello.txt
/root

自定义函数

基本语法

[ function ] funname[()]
{
Action;
[return int;]
}

调用直接写函数名:funname [值]

例子:
计算输入两个参数的和

#!/bin/bash

function getSum(){
        SUM=$[$n1+$n2]
        echo "和是:$SUM"
}
read -p "输入第一个数:" n1
read -p "输入第二个数:" n2

#调用getSum
getSum $n1 $n2

[root@nyh shell]# chmod 744 zdyhs.sh 
[root@nyh shell]# ./zdyhs.sh 
输入第一个数:1
输入第二个数:2
和是:3

猜你喜欢

转载自blog.csdn.net/qq_36901488/article/details/82942125