大数据技术之Shell 第8章 函数

第7章read读取控制台输入

1)基本语法

read(选项)(参数)

选项:

-p:指定读取值时的提示符;

-t:指定读取值时等待的时间(秒)。

参数

​ 变量:指定读取值的变量名

2)案例实操

提示7秒内,读取控制台输入的名称

[root@hadoop101 datas]$ touch read.sh
[root@hadoop101 datas]$ vim read.sh

#!/bin/bash

read -t 7 -p "Enter your name in 7 seconds " NAME
echo $NAME

[root@hadoop101 datas]$ ./read.sh 
Enter your name in 7 seconds xiaoze
xiaoze

第8章 函数

8.1 系统函数

8.1.1 basename

1)基本语法

basename [string / pathname] [suffix] (功能描述:basename命令会删掉所有的前缀包括最后一个(‘/’)字符,然后将字符串显示出来。

选项:

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

2)案例实操

截取该/home/atguigu/banzhang.txt路径的文件名称

[root@hadoop101 datas]$ basename /home/atguigu/banzhang.txt 
banzhang.txt
[root@hadoop101 datas]$ basename /home/atguigu/banzhang.txt .txt

banzhang

8.1.2 dirname

1)基本语法

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

2)案例实操

获取banzhang.txt文件的路径

[root@hadoop101 ~]$ dirname /home/atguigu/banzhang.txt 
/home/atguigu

8.2 自定义函数

1)基本语法

[ function ] funname[()]
{

	Action;
	[return int;]
}
funname

2)经验技巧

(1)必须在调用函数地方之前,先声明函数,shell脚本是逐行运行。不会像其它语言一样先编译。

(2)函数返回值,只能通过$?系统变量获得,可以显示加:return返回,如果不加,将以最后一条命令运行结果,作为返回值。return后跟数值n(0-255)

3)案例实操

计算两个输入参数的和

[root@hadoop101 datas]$ touch fun.sh

[root@hadoop101 datas]$ vim fun.sh
#!/bin/bash
function sum()
{
  s=0
  s=$[ $1 + $2 ]
  echo "$s"
}
read -p "Please input the number1: " n1;
read -p "Please input the number2: " n2;
sum $n1 $n2;

[root@hadoop101 datas]$ chmod 777 fun.sh
[root@hadoop101 datas]$ ./fun.sh 
Please input the number1: 2
Please input the number2: 5
7

IT学习网站

牛牛IT网站

Shell 视频教程推荐

跟着360架构师 学习Shell脚本编程

链接:https://pan.baidu.com/s/1BcYMz5Ov9OpbaoFVrCS2lw
提取码:150c
–来自百度网盘超级会员V4的分享

Shell 高阶开发实战
链接:https://pan.baidu.com/s/1J1Y_htCmru6ujUZVzyIKJA
提取码:i3rn

失效➕V:x923713

QQ交流群 欢迎加入

WechatIMG135
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值