Linux入门(十八)read&函数

read 读取控制台输入

基本语法

read 选项 参数

选项

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

-t 指定读取值时等待的时间(秒),如果没有在指定的时间内输入,就不再等待了

参数

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

实例:

1、读取控制台输入一个num值

2、读取控制台输入一个num值,在10秒内输入

bash 复制代码
vi test_read.sh
#!/bin/bash
#读取控制台输入一个num值
read -p "请输入一个num1=" num1
echo "输入的num1=$num1"
#读取控制台输入一个num值,在10秒内输入

read -t 10 -p "请输入一个num2=" num2

echo "输入的num2=$num2"

函数:系统函数和自定义函数
basename

功能:返回完整路径最后/的部分,常用于获取文件名

语法

basename [pathname] [suffix]

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

功能:返回完整路径最后/前面的部分,常用于返回路径部分

实例

1、请返回/root/test_shell_code/test_read.sh 的test_read.sh部分

bash 复制代码
basename /root/test_shell_code/test_read.sh
basename /root/test_shell_code/test_read.sh .sh

2、请返回/root/test_shell_code/test_read.sh 的/root/test_shell_codebuf

bash 复制代码
 dirname /root/test_shell_code/test_read.sh .sh

自定义函数

基本语法

function \] funname \[()

{

代码

reutrn int;

}

调用 直接写函数名:funame [值]

实例

1、计算输入的两个参数的和,getSum

bash 复制代码
 vi  test_fun.sh
 #!/bin/bash
function getSum(){
        SUM=$[$1+$2]
        echo "总和=$SUM"
}
read -p "请输入一个数n1=" n1
read -p "请输入一个数n2=" n2
getSum $n1 $n2

如果想要getSum 函数在别的sh文件里调用

bash 复制代码
 vi  test_fun.sh
  #!/bin/bash
function getSum(){
        SUM=$[$1+$2]
        echo "总和=$SUM"
}
vi test_fun2.sh
#!/bin/bash
#导入sh 文件
#source /root/test_shell_code/test_fun.sh
#或者使用简写
. /root/test_shell_code/test_fun.sh
read -p "请输入一个数n1=" n1
read -p "请输入一个数n2=" n2
getSum $n1 $n2
相关推荐
花小璇学linux13 分钟前
imx6ull-驱动开发篇31——Linux异步通知
linux·驱动开发·嵌入式软件
shelutai21 分钟前
ubuntu 编译ffmpeg6.1 增加drawtext,libx264,libx265等
linux·ubuntu·ffmpeg
runfarther33 分钟前
搭建LLaMA-Factory环境
linux·运维·服务器·python·自然语言处理·ai编程·llama-factory
百思可瑞教育1 小时前
Spring Cloud Gateway 负载均衡全面指南
运维·负载均衡·北京百思可瑞教育·百思可瑞教育·北京百思教育
hello_ world.1 小时前
RHCA10NUMA
linux
神秘人X7072 小时前
Linux高效备份:rsync + inotify实时同步
linux·服务器·rsync
轻松Ai享生活2 小时前
一步步学习Linux initrd/initramfs
linux
轻松Ai享生活2 小时前
一步步深入学习Linux Process Scheduling
linux
zzywxc7873 小时前
AI 行业应用:金融、医疗、教育、制造业领域的落地案例与技术实现
android·前端·人工智能·chrome·金融·rxjava
绵绵细雨中的乡音3 小时前
网络基础知识
linux·网络