在本指南中,我们将向 Linux 新手展示如何可靠地存储自定义的 shell 脚本,解释如何编写 shell 函数和函数库,以及如何在其它的脚本中使用函数库中的函数。 -- Aaron Kili
本文导航
-Shell 脚本要存储在何处 …… 08%
-创建你自己的 Shell 函数和函数库 …… 28%
-如何从函数库中调用函数 …… 64%
编译自: http://www.tecmint.com/write-custom-shell-functions-and-libraries-in-linux/
作者: Aaron Kili
译者: wcnnbdk1
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
$ mkdir ~/bin
$ mkdir -p ~/lib/sh
函数名() { 一系列的命令 }
showDATE() {date;}
$ showDATE
#!/bin/bash
### Function to clearly list directories in PATH
showPATH() {
oldifs="$IFS" ### store old internal field separator
IFS=: ### specify a new internal field separator
for DIR in $PATH<br> do<br> echo $DIR<br> done
IFS="$oldifs" ### restore old internal field separator
}
### Function to show logged user
showUSERS() {
echo -e “Below are the user logged on the system:\n”
w
}
### Print a user’s details
printUSERDETS() {
oldifs="$IFS" ### store old internal field separator
IFS=: ### specify a new internal field separator
read -p "Enter user name to be searched:" uname ### read username
echo ""
### read and store from a here string values into variables
### using : as a field delimiter
read -r username pass uid gid comments homedir shell <<< "$(cat /etc/passwd | grep "^$uname")"
### print out captured values
echo -e "Username is : $username\n"
echo -e "User&#x27;s ID : $uid\n"
echo -e "User&#x27;s GID : $gid\n"
echo -e "User&#x27;s Comments : $comments\n"
echo -e "User&#x27;s Home Dir : $homedir\n"
echo -e "User&#x27;s Shell : $shell\n"
IFS="$oldifs" ### store old internal field separator
}
$ . /path/to/lib
或
$ source /path/to/lib
#!/bin/bash
### include lib
. ~/lib/sh/libMYFUNCS.sh
### use function from lib
printUSERDETS
### exit script
exit 0
$ chmod 755 test.sh
$ ./test.sh
欢迎光临 51学通信论坛2017新版 (http://bbs.51xuetongxin.com/) | Powered by Discuz! X3 |