天天看點

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() {

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,如需轉載請自行聯系原作者

繼續閱讀