shell 常见操作之 read 与 函数

shell 常见操作

1 read读取控制台输入

1)基本语法

read (选项) (参数)

选项:

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

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

参数

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

2)案例实操

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

[xiao @hadoop105 datas]$ touch read.sh
[xiao @hadoop105 datas]$ vim read.sh

#!/bin/bash

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

[xiao @hadoop105 datas]$ chmod 777 read.sh 
[xiao @hadoop105 datas]$ ./read.sh 
Enter your name in 7 seconds:huxiao
huxiao

2 函数

2.1 系统函数

1)basename

1)基本语法

​ basename [string / pathname] [suffix] (功能描述:basename命令会删掉所有的前缀包

括最后一个(‘/’)字符,然后将字符串显示出来。

​ 选项:

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

2)案例实操

截取该/home/xiao/datas/while.sh路径的文件名称

[xiao @hadoop105 datas]$ basename /home/xiao/datas/while.sh 
while.sh
[xiao @hadoop105 datas]$ basename /home/xiao/datas/while.sh .sh
while

2)dirname

1)基本语法

dirname 文件绝对路径 (功能描述:从给定的包含绝对路径的文件名中去除文件名(非目

录的部分),然后返回剩下的路径(目录的部分))

2)案例实操

获取while.sh文件的路径

[xiao @hadoop105 datas]$ dirname /home/xiao/datas/while.sh 
/home/atguigu/datas

2.2 自定义函数

1)基本语法

[ function ] funname[()]

{

​ Action;

​ [return int;]

}

2)经验技巧

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

样先编译。

(2)函数返回值,只能通过$?系统变量获得,可以显示加:return返回,如果不加,将

以最后一条命令运行结果,作为返回值。return后跟数值n(0-255)

3)案例实操

计算两个输入参数的和

[xiao @hadoop105 datas]$ touch fun.sh
[xiao @hadoop105 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;


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

版权声明:本文为weixin_49063354原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。