What is a function? Why do we use a function?
I. Related knowledge of functions
The function is to package the code with a specific function and provide an interface for use. The advantage of this is that code reuse can be achieved on one hand, for example: many object-oriented languages, like many classes and methods (functions) provided by Java, on the other hand, for modular programming of code, which enables multiple people to develop code at the same time.
The main function of functions in shell is to implement code reuse, of course, the use of functions than writing code can be more concise and easy to read code.
How do I define a function in the shell?
Syntax format:
function F_name {
function body
}
Or
F_name () {
function body
}
Ii. Examples of functions
#!/bin/bash# description: copies an external command itself and the library file it relies on to the specified path # version:0.0# date:2014-07-23# author: alex# license: gpl# analog root file system ch_root= "/mnt/sysroot" [ ! -d $ch _root ] && mkdir $ch _rootbincopy () {if which $1 &>/dev/null; then# local defines a local variable, its scope is this function, generally we try to use local variables here, instead of using global variables local cmd_path= ' which -- Skip-alias $1 ' local bin_dir= ' dirname $1 ' [ -d ${ch_root}${bin_dir} ] | | mkdir -p ${ch_root}${bin_dir}[ -f ${ch_root}${cmd_path} ] | | cp $cmd _path ${ch_root}${bin_dir}# return Returns the status value of a function is a number 0-255return 0elseecho "Command not found." Return 1fi}libcopy () {lib_list=$ (ldd ' which --skip-alias $1 ' | grep - eo '/[^[:space:]]+ ') for loop in $lib _list;dolocal lib_dir= ' dirname $Loop ' [ -b ${ch_root}${lib_dir} ] | | mkdir -p ${ch_root}${lib_dir}[ -f ${ch_root}${loop} ] | | cp $loop ${ch_root}${lib_dir}done}read -p "Please input a command: " commandwhile [ " $command != "quit"  ];d oif bincopy $command ;thenlibcopy $commandfiread -p "please input a command: " Commanddone
This article is from the "Upstream Cold" blog, please be sure to keep this source http://guoting.blog.51cto.com/8886857/1528506
Three functions of Linux shell programming