9.1 System functions
1. basename basic syntax
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, basename will remove the suffix in pathname or string.
2. Case Practice
(1) Intercept the file name of the /home/atguigu/banzhang.txt path
[atguigu@hadoop101 datas]$ basename /home/atguigu/banzhang.txt
banzhang.txt
[atguigu@hadoop101 datas]$ basename /home/atguigu/banzhang.txt .txt
ban zhang
3. Basic syntax of dirname
dirname file absolute path (function description: remove the file name (non-directory part) from the given file name containing the absolute path, and then return the remaining path (directory part))
4. Case Practice
(1) Obtain the path of the banzhang.txt file
[atguigu@hadoop101 ~]$ dirname /home/atguigu/banzhang.txt
/home/atguigu
9.2 Custom functions
1. basic grammar
[ function ] funname[()]
{
Action;
[return int;]
}
funname
2. Skills
(1) The function must be declared before calling the function, and the shell script is run line by line. Does not compile first like other languages.
(2) The return value of the function can only be obtained through the $? system variable, which can be displayed and added: return return, 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 the 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 data]$ ./fun.sh
Please input the number1: 2
Please input the number2: 5
7