linux脚本read读取print,Shell 脚本(四) ”read 读取控制台输入” 与 “函数”

八、read 读取控制台输入

1、基本语法

read(选项)(参数)

选项:

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

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

参数

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

2、案例实操

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

[root@rich datas]# touch read.sh

[root@rich datas]# vim read.sh

#!/bin/bash

read -t 7 -p "input your name " NAME

echo $NAME

3336262

执行脚本:

[root@rich datas]# bash read.sh

input your name

[root@rich datas]# dfads

bash: dfads: 未找到命令...

[root@rich datas]# bash read.sh

input your name wenmin

wenmin

3336262

注: 当input your name 提示的7秒过了之后,退出控制台,不能进行输入NAME; 7秒内将参数输入,便可以被接受到,并使用echo进行打印。

九、函数

1、系统函数

1.1、basename 基本语法

basename [string/pathname] [suffix]

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

选项:

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

1.2、案例实操

(1)截取该 路径的文件名称

[root@rich datas]# basename /home/wenmin/datas/batch.sh

batch.sh

[root@rich datas]# basename /home/wenmin/datas/batch.sh .sh

batch

3336262

1.3、 dirname基本语法

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

1.4、案例实操

(1)获取 batch.sh 文件的路径

[root@rich datas]# dirname /home/wenmin/datas/batch.sh

/home/wenmin/datas

3336262

2、自定义函数

2.1 基本语法

[ function ] funname[()]

{

Action;

[return int;]

}

funname

3336262

2.2 经验技巧

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

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

2.3 案例实操

(1)计算两个输入参数的和

[root@rich datas]# touch sum.sh

[root@rich datas]# vim sum.sh

#!/bin/bash

function sum()

{

s=0;

s=$[$1+$2]

echo $s

}

read -p "input your parameter1:" p1

read -p "input your parameter2:" p2

sum $p1 $p2

3336262

执行 sum.sh 脚本

[root@rich datas]# bash sum.sh

input your parameter1:1

input your parameter2:2

3

3336262

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值