zoukankan      html  css  js  c++  java
  • Shell 读取控制台输入/函数

    一、read读取控制台输入

    1、基本语法

    read(选项)(参数)
    
    选项:
    -p:指定读取值时的提示符;
    -t:指定读取值时等待的时间(秒)。
    
    参数
    变量:指定读取值的变量名

    2、案例实操

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

    [root@centos7 shell_test]#  touch read.sh
    [root@centos7 shell_test]#  vim read.sh
    
    #!/bin/bash
    
    read -t 7 -p "Enter your name in 7 seconds " NAME
    echo $NAME

    二、系统函数

    1、basename基本语法

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

    2、案例实操

    截取该 /home/atguigu/banzhang.txt 路径的文件名称

    [root@centos7 shell_test]#  basename /home/atguigu/banzhang.txt
    banzhang.txt
    [root@centos7 shell_test]#  basename /home/atguigu/banzhang.txt .txt
    banzhang

    3、dirname基本语法

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

    4、案例实操

    获取banzhang.txt文件的路径

    [root@centos7 shell_test]#  dirname /home/atguigu/banzhang.txt
    /home/atguigu

    三、自定义函数

    1、基本语法

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

    2、经验技巧

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

    3、案例实操

    计算两个输入参数的和

    [root@centos7 shell_test]#  touch fun.sh
    [root@centos7 shell_test]#  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@centos7 shell_test]#  chmod 777 fun.sh
    [root@centos7 shell_test]#  ./fun.sh 
    Please input the number1: 2
    Please input the number2: 5
    7
  • 相关阅读:
    k8s学习笔记之五:Pod资源清单spec字段常用字段及含义
    k8s学习笔记之四:资源清单定义入门
    k8s学习笔记之三:k8s快速入门
    k8s学习笔记之一:kubernetes简介
    k8s学习笔记之二:使用kubeadm安装k8s集群
    centos7安装elasticsearch6.3.x集群并破解安装x-pack
    Centos6搭建sftp服务器
    底层互害模式,深契民心
    你不视我为子女,我凭什么视你为父母
    nodejs的桌面应用(electron)
  • 原文地址:https://www.cnblogs.com/jwen1994/p/14917694.html
Copyright © 2011-2022 走看看