在.bashrc文件中定义函数

  在命令行上直接定义shell函数的明显缺点是当退出shell时,函数就消失了,对于复杂的函数来说,这可能会是个问题。
  一个简单的方法就是每次启动新shell的时候都会自动加载所需要的函数。
  最好的办法就是.bashrc文件。bash shell会在每次启动时在主目录查找这个文件,不管是交互式的还是从现有shell中启动一个新的shell
1、直接定义函数
  可以直接在主目录的.bashrc文件中定义函数。.bashrc的路径一搬为 home/linux用户名/  许多Linux发行版已经在.bashrc文件中定义了一些东西了,所以注意别删掉这些内容,只要在已有文件的末尾上加上你写的函数就行了。类似如下:

# .bashrc

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

function addem {
  echo $[ $1 + $2 ]
}
# User specific aliases and functions

其中

function addem {
  echo $[ $1 + $2 ]
}

是用户自行添加的。

直到下次启动新的bash shell 时该函数才会生效。添加并启动bash shell后,你就能在系统上任意地方使用该函数了。

2、读取函数文件
只要是在shell脚本中,你都可以用source命令(或者它的别名点操作符)来将已有库文件中的函数添加到你的.bashrc脚本中:

# .bashrc

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

/home/rich/lobraries/myfuncs

# User specific aliases and functions

确保包含了引用库文件的正确路径,以便于bash shell来查找该文件。下次启动shell时,库中的所有函数都可以在命令行界面下使用了:

$ addem 10 5
15
$ multem 10 5
50
$divem 10 5
2

更好一点的是,shell还会将定义好的函数传给与shell进程,这样这些函数在该shell会话中的任何shell脚本中也都可以用。你可以写个脚本来测试,直接使用这些函数而不用单独定义或读取它们:

#!/bin/bash
# using functions defined in a library 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 th is: $result2"
echo "The result of dividing them is: $result3"

运行后输出为:

The result of adding them is: 15
The result of multiplying them is:50
the result of dividing them is:2

甚至不用读取库文件,这些函数也能在shell脚本中还好的工作。

原文地址:https://www.cnblogs.com/jacson/p/4800903.html