当前位置:网站首页>Shell system learning function
Shell system learning function
2022-07-30 10:14:00 【edenliuJ】
目录
Output the return value to standard output
The definition of the function library file
函数
什么是函数
A function is a collection of relatively independent sets of code,形成一个代码块,A specific function has been completed.It's the same as functions in other programming languages,从本质上讲,A function is a mapping of a function name to a block of code.
函数的定义
ShellThere are two ways to define a function,结果是一样的.
#第一种定义方式
function_name ()
{
statement1
...
}
#第二种定义方式
function function_name ()
{
statement1
...
}There is one more in front of the second way of definitionfunction关键字.function_name表示函数名,命名规则和变量名一样:可以包含字母,数字,下划线;只能以字母或者下划线开头.Users should try to name with meaningful English words.
在Shell语言中,A function definition must precede a function call,不然会报错
command not found
函数的调用
How and where to call the functionShellThe script is the same way,调用语法如下:
function_name param1 param2 ...下面看个简单的例子:
#!/bin/bash
#定义函数
getCurrentTime()
{
echo "`date`"
}
#调用函数
getCurrentTime结果如下:
[email protected]:~/Documents/Shell/6$ ./6-2.sh
Thu 28 Jul 2022 02:17:28 AM PDT
ShellThe functions in it are also the same as in common programming languages,可以嵌套调用,A function can call another function,But it also follows the principle of defining first and calling later,下面看示例:
#!/bin/bash
Lea()
{
echo "Hello, I am Lea!"
}
Eden()
{
echo "Hello, I am John!"
}
sayHello()
{
Lea
Eden
}
sayHello结果如下:
[email protected]:~/Documents/Shell/6$ ./6-3.sh
Hello, I am Lea!
Hello, I am John!
函数的返回值
This is quite different from other programming languages.
The first one is that it does not return a value,After the operation is completed, the purpose is achieved.这在Shell中非常常见.
如果一定要返回值,有如下两种方式:
使用return返回
我们可以用return返回,然后使用$?System variables are obtainedreturn的值
Shell的returnReturn can only return0~255之间的整数,This is the so-called status code.如果超过这个范围,The returned value is wrong,下面举个简单例子:
#!/bin/bash
func()
{
return 257
}
func
echo $?结果如下:
[email protected]:~/Documents/Shell/6$ ./6-4.sh
1
Output the return value to standard output
在函数中,The user writes the data to be returned to standard output(stdout),一般使用echo语句来完成,Then assign the result of the function's execution to a variable in the calling program,That's what I said in the previous article 命令替换 .
使用``或者$()The command get function assigns the value output to standard output to an lvalue,请看示例:
#!/bin/bash
func1()
{
echo "123"
}
result=$(func1)
result1=`func1`
echo $result
echo $result1结果是:
[email protected]:~/Documents/Shell/6$ ./6-4.sh
123
123
This method can return any form of value,不局限于整数,比return的方式更加的强大.
If we call in a functionechoWhat will be the result of the two?看例子:
#!/bin/bash
func1()
{
echo "Hello world"
echo "123"
}
func1
result="$(func1)"
result1=`func1`
echo $result
echo $result1
结果是:
[email protected]:~/Documents/Shell/6$ ./6-4.sh
Hello world
123
Hello world 123
Hello world 123
从结果上来看,The returned value puts bothechoThe outputs are combined,中间加了一个空格.
函数和别名
在Shell中,A concept similar to functions is aliasing.An alias is oneShellAbbreviation or mapping for a command,The syntax for aliases is as follows:
#设置别名
alias alias_name="command"
#删除别名
unalias alias_name
commandA command is a complete command,可以带参数.
与函数相比,The function of aliases is relatively simple,The main differences are as follows:
- Users cannot assign aliases to a group of commands
- The parameter list cannot be manipulated through system variables in an alias
Let's take an example of an alias call:
#!/bin/bash
shopt -s expand_aliases
alias ls="ls -l"
ls结果如下
[email protected]:~/Documents/Shell/6$ ./6-5.sh
total 16
-rwxrwxr-x 1 eden_ubuntu eden_ubuntu 95 Jul 28 02:17 6-2.sh
-rwxrwxr-x 1 eden_ubuntu eden_ubuntu 135 Jul 28 02:21 6-3.sh
-rwxrwxr-x 1 eden_ubuntu eden_ubuntu 181 Jul 28 03:09 6-4.sh
-rwxrwxr-x 1 eden_ubuntu eden_ubuntu 56 Jul 28 03:26 6-5.sh
如果没有第2行的 shopt -s expand_aliases,在Shell脚本中aliasThe command is invalid.但是在ShellNot needed in the console,我们可以试试:
[email protected]:~/Documents/Shell/6$ alias ls="ls -l"
[email protected]:~/Documents/Shell/6$ ls
total 16
-rwxrwxr-x 1 eden_ubuntu eden_ubuntu 95 Jul 28 02:17 6-2.sh
-rwxrwxr-x 1 eden_ubuntu eden_ubuntu 135 Jul 28 02:21 6-3.sh
-rwxrwxr-x 1 eden_ubuntu eden_ubuntu 181 Jul 28 03:09 6-4.sh
-rwxrwxr-x 1 eden_ubuntu eden_ubuntu 56 Jul 28 03:26 6-5.sh
函数可以直接在ShellConsole input definition:
删除函数
命令如下:
unset function_name全局变量和局部变量
局部变量在函数中定义,Prefix the defined variable namelocal关键字.除了这样,All other defined variables are global variables.Include variables defined in functions.
函数参数
There was a previous article devoted to passing parameters:ShellThe direction of systematic learningShell脚本传递参数
主要熟悉$#,$n,[email protected],$*,#?,getopts,getopt,shift的用法
indirect pass
The so-called indirect parameter passing is to pass the parameter through the value of one variable as the variable name of another variable,Around in the middle.语法如下:
${!var_name}
Let's say there are two variables
var=name
name=Eden我们可以将Eden这个值通过${name}传递过去,也可以用${!var}传递过去.
传递数组参数
严格的来说,ShellPassing arrays as arguments to functions is not supported,However, the user can still display the array transmission through some workarounds.
The user can expand the elements of the array,It is then passed to the function as multiple arguments separated by spaces.示例如下:
#!/bin/bash
func()
{
echo "number of elements is $#."
while [ $# -gt 0 ]
do
echo "$1"
shift
done
}
array=(a b "c d" e)
func "${array[@]}"结果如下:
[email protected]:~/Documents/Shell/6$ ./6-6.sh
number of elements is 4.
a
b
c d
e
通过"${array_name[@]}"或者"${array_name[*]}"都可以实现目标
函数库文件
The definition of the function library file
Creating a function library file is similar to writing oneShell脚本,The difference is that the function library file only contains functions,There is no external executable code.举个简单的例子:
#!/bin/bash
error()
{
echo "ERROR:" [email protected] 1>&2
}The above content is a function library file,只有函数.Because the function library file is loaded and executed by the main program,So the user does not need to have executable permissions,Read permission is sufficient.
函数库文件的调用
在Shell中,The command to load the function library file is . ,i.e. an origin,其语法如下:
. filename
filename表示库文件的名称,可以使用相对路径,也可使用绝对路径.示例如下:
#!/bin/bash
#Load library files
. 6-7.sh
error "cannot find file"结果如下:
[email protected]:~/Documents/Shell/6$ ./6-8.sh
ERROR: cannot find file
The corresponding function library file must be loaded before calling the corresponding function,不然会报错:command not found.
小结
This article focuses on the definition of functions,调用,返回值,传参,And the definition and call of the function library file.Focus on the return value,传参,Use of function library files.
边栏推荐
- 大数据产品:标签体系0-1搭建实践
- ThreadLocal内存泄漏是伪命题?
- MFCC转音频,效果不要太逗>V<!
- The creation of a large root heap (video explanation)
- 606. 根据二叉树创建字符串(视频讲解!!!)
- 国外资源加速下载器,代码全部开源
- leetcode 剑指 Offer 47. 礼物的最大价值
- 论文阅读:SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers
- Soft test system architects introductory tutorial | system operation and software maintenance
- shell script
猜你喜欢

梅科尔工作室-看鸿蒙设备开发实战笔记六—无线联网开发

Re16: Read the paper ILDC for CJPE: Indian Legal Documents Corpus for Court Judgment Prediction and Explanation

Multithreading--the usage of threads and thread pools

再有人问你分布式事务,把这篇扔给他

Version management of public Jar packages

Materialist Dialectics - Conditionalism

梅科尔工作室-看鸿蒙设备开发实战笔记四——内核开发

BERT预训练模型系列总结

leetcode 剑指 Offer 25. 合并两个排序的链表

PyQt5-用像素点绘制正弦曲线
随机推荐
Always remember: one day you will emerge from the chrysalis
百度paddleocr检测训练
实战演练 | 在 MySQL 中计算每日平均日期或时间间隔
新一代开源免费的终端工具,太酷了
快解析结合用友时空
SST-Calib:结合语义和VO进行时空同步校准的lidar-visual外参标定方法(ITSC 2022)
(***重点***)Flink常见内存问题及调优指南(一)
ThreadLocal内存泄漏是伪命题?
(文字)无框按钮设置
知识图谱之Cypher语言的使用
唯物辩证法-条件论
神秘的APT攻击
idea2021+Activiti [the most complete note one (basic use)]
判断一颗树是否为完全二叉树——视频讲解!!!
ospf2双点双向重发布(题2)
软考 系统架构设计师 简明教程 | 案例分析 | 需求分析
STM32CubeMX配置生成FreeRTOS项目
再有人问你分布式事务,把这篇扔给他
通过构建一个顺序表——教你计算时间复杂度和空间复杂度(含递归)
A new generation of free open source terminal tool, so cool