shell腳本之函數的定義及使用
函數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() {
read -p "Enter directory: " dir
if [ -d $dir ]; then
rm -rf $dir
echo "目錄$dir刪除完成"
else
echo "目錄$dir不存在"
fi
}
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
編寫腳本,實現用戶管理功能
#!/bin/bash
#
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刪除完成"
else
echo "用戶$1不存在"
fi
}
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
echo
read -p "請輸入要修改的SHELL: " new_sh_name
usermod -s $new_sh_name $name
echo "用戶$name的SHELL被修改為$new_sh_name"
else
echo "用戶$name不存在"
fi
}
cat << eof
===============
用戶管理
1、創建用戶
2、刪除用戶
3、修改用戶SHELL
4、退出腳本
===============
eof
echo
while true; do
read -p "請輸入你的選擇:" choice
case $choice in
1)
createUser
;;
2)
read -p "Enter user: " name
removeUser $name
;;
3)
modifyUser
;;
4)
exit 0
;;
*)
echo "輸入錯誤!"
;;
esac
done
nginx服務控制腳本:
安裝nginx
[[email protected] ~]# yum install -y gcc pcre-devel zlib-devel openssl-devel
[[email protected] ~]# tar xf nginx-1.11.4.tar.gz
[[email protected] ~]# cd nginx-1.11.4/
[[email protected] nginx-1.11.4]# ./configure --prefix=/usr/local/nginx
[[email protected] nginx-1.11.4]# make && make install
腳本如下:
#!/bin/bash
#
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
fi
}
status() {
if [ -e $nginx_pid_file ]; then
echo "服務nginx(PID `cat $nginx_pid_file`) is running..."
else
echo "服務nginx is stopped..."
fi
}
if [ -z $1 ]; then
echo "使用:$0 {start|stop|restart|reload|status}"
exit 9
fi
case $1 in
start)
start
;;
stop)
stop
;;
restart)
stop
sleep 2
start
;;
reload)
reload
;;
status)
status
;;
*)
echo "使用:$0 {start|stop|restart|reload|status}"
exit 8
esac
本文出自 “lyw666” 博客,請務必保留此出處http://lyw666.blog.51cto.com/12823216/1957418
shell腳本之函數的定義及使用