Shell_read_function

1.read
2.function

read to read console input
1. Basic grammar
read(选项)(参数)
选项:

-p: Specify the prompt when reading the value;
-t: Specify the waiting time (seconds) when reading the value.
Parameter
Variable: Specify the name of the variable to read the value

2. Case practice

(1) Within 7 seconds of the prompt, read the name entered on the console

[atguigu@hadoop101 datas]$ touch read.sh
[atguigu@hadoop101 datas]$ vim read.sh

#!/bin/bash

read -t 7 -p "Enter your name in 7 seconds " NAME
echo $NAME

[atguigu@hadoop101 datas]$ ./read.sh 
Enter your name in 7 seconds xiaoze
xiaoze
System function
1. Basic syntax of basename

basename [string / pathname] [suffix] (Function description: The basename command will delete all prefixes including the last ('/') character, and then display the string.
Options:
suffix is ​​the suffix, if suffix is ​​specified, The basename will remove the suffix in the pathname or string.

2. Case practice

(1) Intercept the file name of the /home/atguigu/banzhang.txt path

[atguigu@ha	doop101 datas]$ basename /home/atguigu/banzhang.txt 
banzhang.txt
[atguigu@hadoop101 datas]$ basename /home/atguigu/banzhang.txt .txt
banzhang
3. Basic syntax of dirname
dirname 文件绝对路径		(功能描述:从给定的包含绝对路径的文件名中去除文件名(非目录的部分),然后返回剩下的路径(目录的部分))
4. Case practice

(1) The path to obtain the banzhang.txt file

[atguigu@hadoop101 ~]$ dirname /home/atguigu/banzhang.txt 
/home/atguigu
Custom function
1. Basic grammar

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



2. Experience skills

(1) The function must be declared before calling the function place. The shell script is run line by line. It will not be compiled first like other languages.
(2) The return value of the function can only be obtained through the $? system variable, which can be displayed plus: return returns, if not added, the result of the last command will be used as the return value. return followed by the value n (0-255)

3. Case practice

(1) Calculate the sum of two input parameters

[atguigu@hadoop101 datas]$ touch fun.sh
[atguigu@hadoop101 datas]$ 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;

[atguigu@hadoop101 datas]$ chmod 777 fun.sh
[atguigu@hadoop101 datas]$ ./fun.sh 
Please input the number1: 2
Please input the number2: 5
7

Guess you like

Origin blog.csdn.net/qq_43141726/article/details/114495766