快速入门Shell脚本(4)——常用的函数操作

在这里插入图片描述
         前几篇已经给大家介绍了shell脚本,前几篇都算是入门,今天给大家带来一些比较复杂的操作(函数),本篇博客,我们来聊一聊shell脚本中的函数操作

1.函数的优点

函数的优点

  1. 代码模块化
  2. 调用方便
  3. 节省内存
  4. 代码量小
  5. 拍错简单

2.rand 在控制输入数据并读取控制台的数据输出

2.1 基本语法

read(选项)(参数)
选项

  • -p:指定读取值时的提示符;
  • -t:指定读取值时等待时间(秒)。
    参数
  • 变量:指定读取值得变量名
    解释: 比如说java中new Scanner(System.in).nextLine();意思一样,话不多了直接上代码。
System.out.println("输入一个字符串");
Scanner input = new Scanner(System.in);
String result = input.nextLine();
System.out.println(result);

2.2. 案例实操

10秒内,在控制台输入数据,并将数据输出到控制台

[root@node01 shell]# vim read.sh 
#!/bin/bash
read -t 10 -p "Enter you name in 10 secodes " NAME ; echo $NAME
[root@node01 shell]# sh read.sh 
Enter you name in 10 secodes 22
22

3.系统自带函数

3.1 basename 基本语法

basename[string/pathname][suffix] (功能描述:basename命令会去掉所有的前缀包括最有一个(’/’)字符然后将字符串显示出来)。
选项:
suffix 为后缀,如果suffix被制定了,basename会将pathname或string中的suffix去掉。

3.2. 实例实操

截取该/opt/shell/helloword.sh 路径的名称

[root@node01 shell]# basename /opt/shell/helloword.sh 
helloword.sh
[root@node01 shell]# basename /opt/shell/helloword.sh  .sh
helloword

3.3 dirname 基本语法

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

3.4 实例实操

获取helloword.sh 文件路径

[root@node01 shell]# dirname /opt/shell/helloword.sh 
/opt/shell

4.自定义函数

4.1 基本语法

[funcation] funname[0]
{
    Action;
    [return int;]
}
funame

4.2使用技巧

  • 必须在调用函数地方之前,先声明函数,shell脚本是逐个运行不会像其它语言一样先变异
  • 函数返回值,只能通过$?系统变量获得,可显示加:return返回,如果不加,将以最后一条命令运行结果,作为返回值,return后跟数值n(0-255)

4.3 案例实操

计算两个输入参数的和

[root@node01 shell]# 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@node01 shell]# sh fun.sh 
Please input the number1: 10
Please input the number2: 20
30

猜你喜欢

转载自blog.csdn.net/qq_43791724/article/details/107631102