Sometimes we use a function often, it is very troublesome to assign a value in each script, this time we can write the function that we use frequently in the form of function library.
A very simple little example: do we need to know which version of the operating system is currently running? Of course it's easy to get it if we use the uname command directly, but here we need to practice using the library:
1: First write a text file: The main content of this file is to find out the current version of the system is running.
[[email protected] ~]# vim Library.sh#!/bin/echo warning:this is a library should be sourced! #上面这一行的作用是防止数据库被意外执行 # define function tes T_platform is used to test the current operating system Test_platform () {local osname= ' uname-s ' platform=unknowncase ${osname} in "FreeBSD") platform= " FREEBSD ";; "SunOS") platform= "SOLARIS";; "Linux") platform= "Linux";; Esacreturn 0}
This file is our library function:
2: Write a script call library function, output the current system version information:
[[email protected] ~]# vim test.sh #!/bin/bash# first includes the library in the script file, so that the function source defined in it can be called./library.sh# call Test_ in the function library platformtest_platform# the global variable defined in the output function Test_platform Platformechoecho "Our running platform is $PLATFORM" exit
Then we execute the Execute test.sh script:
[Email protected] ~]# SH test.sh Our running platform is LINUX
A few notes about the library file:
The suffix of the library file is arbitrary, and there is no strict requirement, although we have used the. sh suffix here, but this is not a script file.
Because the library file is not run directly, it is included in other script files, so the library file usually does not have executable permissions:
The placement of the library files is arbitrary, not necessarily in the same directory as the running script, as long as the path is indicated in the script.
Because you do not want the library files to be executed directly by the user, the first line of the library file is usually modified to "#! /bin/echo warning message "in such a way that timely library files are accidentally executed, and warning messages are also output.
This article is from "Custom" blog, declined reprint!
Shell-----Function library Call