函数Function的使用
定义函数
1)
函数名称() {
...
}
2)
function 函数名称 {
调用函数
函数名称
也可以通过位置变量的方式给函数传递参数
例子:
编写脚本,实现目录管理功能,要求使用函数
#!/bin/bash
#
createDir() {
read -p "Enter directory: " dir
if [ -d $dir ]; then
echo "目录$dir存在"
else
mkdir -p $dir
echo "目录$dir创建完成"
fi
removeDir() {
rm -rf $dir
echo "目录$dir删除完成"
echo "目录$dir不存在"
cat << eof
===================
目录管理
1、创建目录
2、删除目录
3、退出脚本
==================
eof
echo
while true; do
read -p "请输入你的选择:" choice
case $choice in
1)
createDir
;;
2)
removeDir
3)
exit 0
*)
echo -e "\033[31m输入错误!\033[0m"
;;
esac
done
编写脚本,实现用户管理功能
createUser() {
read -p "Enter user: " name
if ! id $name &> /dev/null; then
useradd $name
read -p "Enter password: " password
echo "$password" | passwd --stdin $name &> /dev/null
echo "用户$name创建完成"
else
echo "用户$name不存在."
fi
removeUser() {
if id $1 &> /dev/null; then
userdel -r $1
echo "用户$1删除完成"
echo "用户$1不存在"
modifyUser() {
read -p "Enter user: " name
if id $name &> /dev/null; then
sh_name=$(grep "^$name:" /etc/passwd | awk -F: '{print $7}')
echo "用户$name当前的SHELL: $sh_name"
echo
echo "系统当前的SHELL:"
cat -n /etc/shells
read -p "请输入要修改的SHELL: " new_sh_name
usermod -s $new_sh_name $name
echo "用户$name的SHELL被修改为$new_sh_name"
echo "用户$name不存在"
===============
用户管理
1、创建用户
2、删除用户
3、修改用户SHELL
4、退出脚本
echo
read -p "请输入你的选择:" choice
case $choice in
1)
createUser
;;
2)
read -p "Enter user: " name
removeUser $name
3)
modifyUser
4)
exit 0
*)
echo "输入错误!"
esac
nginx服务控制脚本:
安装nginx
[root@shell ~]# yum install -y gcc pcre-devel zlib-devel openssl-devel
[root@shell ~]# tar xf nginx-1.11.4.tar.gz
[root@shell ~]# cd nginx-1.11.4/
[root@shell nginx-1.11.4]# ./configure --prefix=/usr/local/nginx
[root@shell nginx-1.11.4]# make && make install
脚本如下:
nginx_cmd=/usr/local/nginx/sbin/nginx
nginx_conf=/usr/local/nginx/conf/nginx.conf
nginx_pid_file=/usr/local/nginx/logs/nginx.pid
start() {
$nginx_cmd
if [ $? -eq 0 ]; then
echo "服务nginx启动......[ok]"
fi
stop() {
$nginx_cmd -s stop
reload() {
if $nginx_cmd -t &> /dev/null; then
$nginx_cmd -s reload
else
$nginx_cmd -t
status() {
if [ -e $nginx_pid_file ]; then
echo "服务nginx(PID `cat $nginx_pid_file`) is running..."
echo "服务nginx is stopped..."
if [ -z $1 ]; then
echo "使用:$0 {start|stop|restart|reload|status}"
exit 9
fi
case $1 in
start)
start
;;
stop)
stop
restart)
sleep 2
reload)
reload
status)
status
*)
echo "使用:$0 {start|stop|restart|reload|status}"
exit 8
esac
本文转自 北冥有大鱼 51CTO博客,原文链接:http://blog.51cto.com/lyw168/1957418,如需转载请自行联系原作者