SHELL 脚本 “read 读取控制台输入” 与 “函数”

    xiaoxiao2024-10-24  87

    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

    执行脚本:

    [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 注: 当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

    1.3、 dirname基本语法

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

    1.4、案例实操

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

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

    2、自定义函数

    2.1 基本语法

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

    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

    执行 sum.sh 脚本

    [root@rich datas]# bash sum.sh input your parameter1:1 input your parameter2:2 3

    作者:鮀城小帅 来源: 原文:https://blog.csdn.net/weixin_42405670/article/details/89735839 版权声明:本文为博主原创文章,转载请附上博文链接!

    最新回复(0)