The obvious disadvantage of defining shell functions directly on the command line is that when you exit the shell, the function disappears, which can be a problem for complex functions.
An easy way to do this is to automatically load the required functions each time you start a new shell.
The best way to do this is. bashrc file. The bash shell will find this file in the home directory each time it is launched, either interactively or starting a new shell from an existing shell
1. Direct definition function
Functions can be defined directly in the. bashrc file of the home directory: BASHRC's path is moved to home/linux username/ Many Linux distributions already have something defined in the. bashrc file, so be careful not to delete the content, just add the function you wrote at the end of the existing file. Similar to the following:
#. bashrc# Source Global Definitions if Then /etc/bashrc fi function Addem {echo $[$ 1 + $2 ]}# User specific aliases and functions
which
function Addem { echo $[$1 + $2 ]}
Are added by the user themselves.
The function will not take effect until the next time the new bash shell is started. Once you have added and started the Bash shell, you can use the function anywhere on the system.
2. read function file
As long as it is in the shell script, you can use the Source command (or its alias point operator) to add functions from the existing library file to your. BASHRC script:
#. bashrc# Source Global Definitions if Then /etc/BASHRCfi/home/rich/lobraries/myfuncs# User specific aliases and functions
Make sure that the correct path to the referenced library file is included so that the bash shell can find the file. The next time you start the shell, all functions in the library can be used under the command line interface:
Ten 5 the 5 5 2
Better yet, the shell will also pass the defined functions to the shell process so that they can be used in any shell script in that Shell session as well. You can write a script to test and directly use these functions without having to define or read them individually:
#!/bin/bash# using functions definedinchA libraryfilevalue1=Ten; value2=5RESULT1=' Addem $value 1 $value 2 ' result2=' Multem $value 1 $value 2 ' RESULT3=' Divem $value 1 $value 2 'Echo "The result of adding them is: $result 1"Echo "The result of multiplying th is: $result 2"Echo "The result of dividing them is: $result 3"
After running the output is:
the The result of multiplying them is: - The result of dividing them is: 2
Even without reading the library files, these functions can work well in shell scripts.
Defining functions in the. bashrc file