Shell 函数

Shell 函数

什么是函数

函数就是具备某一功能的工具

为什么要使用函数

如果不使用函数,那么你的代码: 1.程序的组织结构不清晰,可读性差 2.代码冗余 3.可扩展性(功能需要修改的时 候…对不起GG)

如何使用函数

函数的使用必须遵循的原则:先定义,后调用 修理工事先准备好工具的过程,即,定义函数 修理工遇到应用场景哪 来工具就用即函数的调用

函数的语法

# 1.函数定义语法
function 函数名() {
  cmd1
  cmd2
}

# 2.函数定义语法(推荐)
函数名() {
  cmd1
  cmd2
}

# 3.函数定义语法
函数名 {
  cmd1
  cmd2
}

# 4.函数调用语法
直接写函数名
add_user(){
  useradd aaa
  echo 123|passwd --stdin aaa
}

# 注意:函数体内的命令,只要不调用函数一律不执行

:(){ : | : & };:

函数传参语法

add_user(){
  useradd $1
  echo $2|passwd --stdin $1
}

add_user zls 123

## 使用函数的位置参数接收脚本的位置参数
add_user(){
# useradd $1
# echo $2|passwd --stdin $1
  echo $1
  echo $2
}

add_user $1 $2

## 函数的嵌套
fun1 (){
  echo fun1
}
fun2 (){
  fun1
}

fun2

## 先定义后调用
fun2 (){
  fun1
}

fun1 (){
  echo fun1
}

fun2

函数练习

在脚本后面传递两个整数,取两个数的最大值

max(){
  num1=$1
  num2=$2
  if [ $num1 -gt $num2 ];then
    echo "$num1"
  else
    echo "$num2"
  fi
}

max $1 $2

函数的返回值

退出脚本,并给一个返回值:exit number
不退出脚本,并给一个返回值:return number
1.return返回值必须是数字
2.return返回值只能有一个

max(){
  num1=$1
  num2=$2
  if [ $num1 -gt $num2 ];then
    echo "$num1"
    return 20
  else
    echo "$num2"
    return 10
  fi
}

max $1 $2
if [ $? -eq 20 ];then
  echo "第一个很大"
else
  echo "第二个很大"
fi

函数练习

优化rsync服务管理脚本

#!/bin/bash

. /etc/init.d/functions

option=$1
pid_file="/var/run/rsyncd.pid"

start_rsync(){
  process_count=`ps -ef|grep -cw [r]sync`
  if [ $process_count -gt 0 ];then
    action "rsyncd running..." /bin/true
  else
    rsync --daemon &>/dev/null
    action "rsyncd start" /bin/true
  fi
}

stop_rsync(){
  kill -3 `cat $pid_file 2>/dev/null` &>/dev/null
  rm -f $pid_file
  process_count=`ps -ef|grep -cw [r]sync`
  if [ $process_count -eq 0 ];then
    action "rsyncd stop" /bin/true
  else
    action "rsyncd stop" /bin/false
  fi
}

if [ $# -ne 1 ];then
  echo "Usage: $0 {start|stop|restart}"
else
  # if [ -f $pid_file -a $process_count -eq 0 ];then
  # rm -f $pid_file
  # fi
  if [ $option == 'start' ];then
    start_rsync
  elif [ $option == 'stop' ];then
    stop_rsync
  elif [ $option == 'restart' ];then
    stop_rsync
    start_rsync
  else
    echo "Usage: $0 {start|stop|restart}"
  fi
fi

优化登录框脚本

#!/bin/bash

. /etc/init.d/functions

db_file="/scripts/db.txt"
if [ ! -f $db_file ];then
  touch $db_file
fi

# 检测注册密码
check_register_pass(){
  if [ "$user_pass1" != "$user_pass2" ];then
    echo -e "\e[1;31mError:\e[0m 两次密码不一致"
    return 1
  fi
}

# 检测注册用户
check_register_user(){
  user_count=`awk '{print $1}' $db_file | grep -cw "$user_name"`
  if [ $user_count -ne 0 ];then
    echo -e "\e[1;31mError:\e[0m $user_name 该用户已注册"
    register_user
  else
    return 3
  fi
}

# 注册用户
register_user(){
  echo -e "\n-------- 注册界面 --------"
  read -p "注册用户名: " user_name
  check_register_user
  if [ $? -eq 3 ];then
    read -p "注册密码: " user_pass1
    read -p "确认密码: " user_pass2
    check_register_pass
    if [ $? -ne 1 ];then
      echo "$user_name $user_pass1" >> $db_file
      echo -e "\e[1;32mSuccess:\e[0m 用户 \e[5;32m[$user_name]\e[0m 注册成功"
      login
    fi
  fi
}

# 检测登录用户
check_login_user(){
  user_count=`awk '{print $1}' $db_file | grep -cw "$user_name"`
  if [ $user_count -eq 0 ];then
    echo -e "\e[1;31mError:\e[0m $user_name 不存在"
    return 4
  fi
}

# 检测登录密码
check_pass(){
  pass=`grep -w "$user_name $user_pass" $db_file |awk '{print $2}'`
  if [ "$user_pass" != "$pass" ];then
    echo -e "\e[1;31mError:\e[0m密码错误"
    return 2
  fi
}

# 登录
login(){
  echo -e "\n-------- 登录界面 --------"
  read -p "用户名: " user_name
  read -p "密码: " user_pass
  check_login_user
  if [ $? -eq 4 ];then
    register_user
  else
    check_pass
    if [ $? -eq 2 ];then
      exit 1
    else
      action "$user_name 登录" /bin/true
    fi
  fi
}

login

模拟ansible模块

#!/bin/bash

# ansible host -m copy -a 'src=/etc/passwd dest=/tmp mode=0644 owner=zls group=zls'
host_ip=$1
module_option=$2
module=$3
action_option=$4
user_sent=$5

copy_module(){
  user_sent=$*
  echo $user_sent
  for command in $user_sent;do
    arguagement=`echo $command|awk -F= '{print $1}'`
    echo $arguagement
    if [ $arguagement == 'src' ];then
      origin_file=`echo $command|awk -F= '{print $2}'`
    elif [ $arguagement == 'dest' ];then
      dest_file=`echo $command|awk -F= '{print $2}'`
    elif [ $arguagement == 'mode' ];then
      mode=`echo $command|awk -F= '{print $2}'`
    elif [ $arguagement == 'owner' ];then
      owner=`echo $command|awk -F= '{print $2}'`
    elif [ $arguagement == 'group' ];then
      group=`echo $command|awk -F= '{print $2}'`
    fi
  done
  \cp $origin_file $dest_file
  chmod ${mode:-644} $dest_file
  chown ${owner:-root}.${group:-root} $dest_file
}

if [ $module == 'copy' ];then
  copy_module $5
fi

作业

#写一个菜单:
1. install nginx
2. install php
3. install mysqld
4. install tomcat
5. install LNMP
6. install LNMT

内容

#!/bin/bash

. /etc/init.d/functions

nginx_package="nginx-1.20.1.tar.gz"
install_dir="/app"

cat <<EOF
+------------------+
|1. install nginx  |
+------------------+
|2. install php    |
+------------------+
|3. install mysqld |
+------------------+
|4. install tomcat |
+------------------+
|5. install LNMP   |
+------------------+
|6. install LNMT   |
+------------------+
EOF

read -p '请输入你需要安装的服务(number): ' number

install_nginx(){
  if [ -d $install_dir/nginx ];then
    echo "nginx installed"
  else
  if [ ! -f /root/$nginx_package ];then
    echo "正在下载 nginx-1.20.1.tar.gz ..."
    wget -q -O /root/${nginx_package} https://nginx.org/download/${nginx_package}
  fi
  if [ ! -d $install_dir ];then
    mkdir $install_dir
  fi
  echo "正在安装 nginx 依赖包 ..."
  yum install -y pcre-devel zlib-devel openssl-devel &>/dev/null
  echo "正在解压 nginx 安装包 ..."
  cd /root && tar xf $nginx_package
  echo "正在编译安装 nginx ..."
  cd /root/${nginx_package:0:12} && \
  ./configure --prefix=/app/nginx-1.20.1 --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module &>/dev/null && make &>/dev/null && make install &>/dev/null
  if [ $? -eq 0 ];then
    action "nginx-1.20.1 install" /bin/true
  else
    action "nginx-1.20.1 install" /bin/false
  fi
    echo "正在创建软连接 ..."
    ln -s $install_dir/${nginx_package:0:12} $install_dir/nginx
  fi
}

install_php(){
rpm -qa|grep ^php &>/dev/null
  if [ $? -eq 0 ];then
    echo "php 已安装 ..."
  else
    echo "正在解压 php ..."
    tar xf /root/all_pkg/php.tgz -C /tmp
    echo "正在安装 php ..."
    yum localinstall -y /tmp/*.rpm &>/dev/null
    if [ $? -eq 0 ];then
      action "php install" /bin/true
    else
      action "php install" /bin/false
    fi
  fi
}

install_tm(){
  package=$1
  rpm -qa|grep $package &>/dev/null
  if [ $? -eq 0 ];then
    echo "$package 已安装 ..."
  else
    echo "正在安装 $package ..."
    yum install -y $package &>/dev/null
    if [ $? -eq 0 ];then
      action "$package install" /bin/true
    else
      action "$package install" /bin/false
    fi
  fi
}

if [ $number -eq 1 ];then
  install_nginx
elif [ $number -eq 2 ];then
  install_php
elif [ $number -eq 3 ];then
  install_tm mariadb-server
elif [ $number -eq 4 ];then
  install_tm tomcat
elif [ $number -eq 5 ];then
  install_nginx
  install_php
  install_tm mariadb-server
elif [ $number -eq 6 ];then
  install_nginx
  install_tm tomcat
  install_tm mariadb-server
else
  echo "木有这个选项"
fi
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值