函数调用
全局函数库
您可以将所有函数存储在称为函数库的函数文件中。您可以将所有功能加载到当前脚本或命令提示符中。加载所有功能的语法如下:
. /path/to/your/functions.sh
创建一个名为 myfunctions.sh 的功能文件:
#!/bin/bash
# set variables
declare -r TRUE=0
declare -r FALSE=1
declare -r PASSWD_FILE=/etc/passwd
##################################################################
# Purpose: Converts a string to lower case
# Arguments:
# $1 -> String to convert to lower case
##################################################################
function to_lower()
{
local str="$@"
local output
output=$(tr '[A-Z]' '[a-z]'<<<"${str}")
echo $output
}
##################################################################
# Purpose: Display an error message and die
# Arguments:
# $1 -> Message
# $2 -> Exit status (optional)
##################################################################
function die()
{
local m="$1" # message
local e=${2-1} # default exit status 1
echo "$m"
exit $e
}
##################################################################
# Purpose: Return true if script is executed by the root user
# Arguments: none
# Return: True or False
##################################################################
function is_root()
{
[ $(id -u) -eq 0 ] && return $TRUE || return $FALSE
}
##################################################################
# Purpose: Return true $user exits in /etc/passwd
# Arguments: $1 (username) -> Username to check in /etc/passwd
# Return: True or False
##################################################################
function is_user_exits()
{
local u="$1"
grep -q "^${u}" $PASSWD_FILE && return $TRUE || return $FALSE
}
函数库加载
您可以将 myfunctions.sh 加载到当前的 shell 环境中,输入:
. myfunctions.sh
. /path/to/myfunctions.sh
创建一个名为 functionsdemo.sh 的脚本:
#!/bin/bash
# Load the myfunctions.sh
# My local path is /home/vivek/lsst2/myfunctions.sh
. /home/vivek/lsst2/myfunctions.sh
# Define local variables
# var1 is not visitable or used by myfunctions.sh
var1="The Mahabharata is the longest and, arguably, one of the greatest epic poems in any language."
# Invoke the is_root()
is_root && echo "You are logged in as root." || echo "You are not logged in as root."
# Find out if user account vivek exits or not
is_user_exits "vivek" && echo "Account found." || echo "Account not found."
# Display $var1
echo -e "*** Orignal quote: \n${var1}"
# Invoke the to_lower()
# Pass $var1 as arg to to_lower()
# Use command substitution inside echo
echo -e "*** Lowercase version: \n$(to_lower ${var1})"
source
source 命令可用于将任何函数文件加载到当前的 Shell 脚本或命令提示符中。它从给定的 FILENAME 中读取并执行命令,然后返回。$PATH 中的路径名用于查找包含 FILENAME 的目录。如果提供了任何 ARGUMENTS,则它们将在执行 FILENAME 时成为位置参数。
source filename [arguments]
source functions.sh
source /path/to/functions.sh arg1 arg2
source functions.sh WWWROOT=/apache.jail PHPROOT=/fastcgi.php_jail
创建一个名为 mylib.sh 的 shell 脚本,如下所示:
#!/bin/bash
JAIL_ROOT=/www/httpd
is_root(){
[ $(id -u) -eq 0 ] && return $TRUE || return $FALSE
}
保存并关闭文件。现在,您可以在脚本 test.sh 中使用以下语法从 mylib.sh 调用和使用函数 is_root():
#!/bin/bash
# Load the mylib.sh using source comamnd
source mylib.sh
echo "JAIL_ROOT is set to $JAIL_ROOT"
# Invoke the is_root() and show message to user
is_root && echo "You are logged in as root." || echo "You are not logged in as root."
我们前面的示例可以使用 source 命令更新,如下所示:
#!/bin/bash
# load myfunctions.sh function file
source /home/vivek/lsst2/myfunctions.sh
# local variable
quote="He WHO Sees me in all things, and ALL things in me, is never far from me, and I am never far from him."
# invoke is_root()
is_root && echo "You are a superuser." || echo "You are not a superuser."
# call to_lower() with ${quote}
to_lower ${quote}
递归函数
递归函数是重复调用自身的函数。递归调用的数量没有限制。创建一个名为 fact.sh 的 shell 脚本:
#!/bin/bash
# fact.sh - Shell script to to find factorial of given command line arg
factorial(){
local i=$1
local f
declare -i i
declare -i f
# factorial() is called until the value of $f is returned and is it is <= 2
# This is called the recursion
[ $i -le 2 ] && echo $i || { f=$(( i - 1)); f=$(factorial $f); f=$(( f * i )); echo $f; }
}
# display usage
[ $# -eq 0 ] && { echo "Usage: $0 number"; exit 1; }
# call factorial
factorial $1
后台函数调用
& 运算符将命令放在后台,并释放终端。您也可以在后台放置一个函数。
name(){
echo "Do something"
sleep 1
}
# put a function in the background
name &
# do something
在执行磁带备份时,您可以显示一系列点(进度条)。这对于用户或操作员显示进度条很有用。创建一个名为 progressdots.sh 的 shell 脚本:
#!/bin/bash
# progressdots.sh - Display progress while making backup
# Based on idea presnted by nixCraft forum user rockdalinux
# Show progress dots
progress(){
echo -n "$0: Please wait..."
while true
do
echo -n "."
sleep 5
done
}
dobackup(){
# put backup commands here
tar -zcvf /dev/st0 /home >/dev/null 2>&1
}
# Start it in the background
progress &
# Save progress() PID
# You need to use the PID to kill the function
MYSELF=$!
# Start backup
# Transfer control to dobackup()
dobackup
# Kill progress
kill $MYSELF >/dev/null 2>&1
echo -n "...done."
echo