当前位置: 首页 > news >正文

shell_81.Linux在命令行中创建使用函数

在命令行中使用函数
在命令行中创建函数
两种方法
单行方式来定义函数:

$ function divem { echo $[ $1 / $2 ]; } 
$ divem 100 5 
20 
$ 


当你在命令行中定义函数时,必须在每个命令后面加个分号,这样 shell 就能知道哪里是命令的起止了:

$ function doubleit { read -p "Enter value: " value; echo $[ $value * 2 ]; } 
$ 
$ doubleit 
Enter value: 20 
40 
$ 

多行方式来定义函数

$ function multem { 
> echo $[ $1 * $2 ] 
> } 
$ multem 2 5 
10 
$ 


在.bashrc 文件中定义函数
直接定义函数

$ cat .bashrc 
# .bashrc 
# Source global definitions 
if [ -r /etc/bashrc ]; then . /etc/bashrc 
fi 
function addem { echo $[ $1 + $2 ] 
} 
$

 
该函数会在下次启动新的 bash shell 时生效。随后你就能在系统中的任意地方使用这个函数了。

源引函数文件
只要是在 shell 脚本中,就可以用 source 命令(或者其别名,即点号操作符)将库文件中的函数添加到.bashrc 脚本中:

$ cat .bashrc 
# .bashrc 
# Source global definitions 
if [ -r /etc/bashrc ]; then . /etc/bashrc 
fi 
. /home/rich/libraries/myfuncs 
$ 
$ addem 10 5 
15 
$ multem 10 5 
50 
$ divem 10 5 
2 
$

shell会将定义好的函数传给子 shell 进程,这些函数能够自动用于该 shell 会话中的任何 shell 脚本。

$ cat test15 
#!/bin/bash 
# using a function defined in the .bashrc file 
value1=10 
value2=5 
result1=$(addem $value1 $value2) 
result2=$(multem $value1 $value2) 
result3=$(divem $value1 $value2) 
echo "The result of adding them is: $result1" 
echo "The result of multiplying them is: $result2" 
echo "The result of dividing them is: $result3" 
$ 
$ ./test15 
The result of adding them is: 15
The result of multiplying them is: 50
The result of dividing them is: 2
$


 

http://www.lryc.cn/news/252971.html

相关文章:

  • 鱼香ROS一键安装命令(支持微信、docker、ros等)
  • 深入理解 Go 函数:从基础到高级
  • 开启三层交换机DHCP服务
  • jspdf+html2canvas浏览器缩放问题
  • 西南科技大学模拟电子技术实验六(BJT电压串联负反馈放大电路)预习报告
  • JS的监听事件
  • JS Object.values()
  • 基于Java SSM人力资源管理系统
  • 人工智能和程序员
  • Unity优化篇:对于unity DrawCall/Mesh/纹理压缩/内存等方面的常规调试和优化手段
  • 学生信息管理系统
  • 纯代码压缩WordPress前端Html
  • Elasticsearch分词器--空格分词器(whitespace analyzer)
  • 【LeetCode】692. 前K个高频单词
  • 在Windows操作系统上使用rtsp simple server和ffmpeg推送录屏视频流
  • 互联网摸鱼日报(2023-12-05)
  • Android 项目的依赖方式
  • ArcGIS提取DEM中的山脉范围
  • 漏洞复现--万户ezoffice wpsservlet任意文件上传
  • TCPDUMP抓包明确显示IP地址和端口号
  • java FTP客户端获取文件流假死问题
  • python使用记录
  • 【Vulnhub 靶场】【Coffee Addicts: 1】【简单-中等】【20210520】
  • codeforces每日两道思维题(第 二 天)
  • 【网络安全】-常见的网站攻击方式详解
  • ElasticSearch学习笔记(一)
  • go写文件后出现大量NUL字符问题记录
  • 【Collection - PriorityQueue源码解析】
  • Javascript_根据截止日期超时自动返回
  • 记录 | vscode设置自动换行