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
  • 相关阅读:
    (数据看成字符串)大端——高尾端,小端——低尾端链接
    ASP.NET 页生命周期概述
    asp.net web 开发登录相关操作的控件LoginName、LoginStatus和LoginView控件使用详解
    Server.MapPath()目录详解
    C# ASP.NET FILEUPLOAD详解
    HTML中id、name、class 区别
    注册表新建 -------DWORD(32-位)
    XSD标准架构-----<xsd:element> 元素详解
    html5学习链接
    关于HSL和HSV颜色空间的详细论述
  • 原文地址:https://www.cnblogs.com/jwen1994/p/14917694.html
Copyright © 2011-2022 走看看