欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

Shell 编程 函数

程序员文章站 2022-04-14 20:45:18
本篇主要写一些 脚本函数的使用。 函数调用 bash !/bin/bash sum(){ s= echo $s } sum [root@localhost ~] vim sum.sh [root@localhost ~] chmod +x sum.sh [root@localhost ~] ./su ......

Shell 编程 函数

本篇主要写一些shell脚本函数的使用。


函数调用

#!/bin/bash
sum(){
  s=`expr 2 + 3`
  echo $s
}
sum
[root@localhost ~]# vim sum.sh
[root@localhost ~]# chmod +x sum.sh 
[root@localhost ~]# ./sum.sh 
5

传递参数

#!/bin/bash
sum(){
  s=`expr $1 + $2`
  echo $s
}
sum 2 3
[root@localhost ~]# vim sum.sh
[root@localhost ~]# ./sum.sh 
5

return

#!/bin/bash
sum(){
  return $(($1 + $2))
}
sum 2 3
echo $?
[root@localhost ~]# vim sum.sh
[root@localhost ~]# ./sum.sh 
5

echo

#!/bin/bash
sum(){
  echo $(($1 + $2))
}
res=$(sum 2 3)
echo $?,$res
[root@localhost ~]# vim sum.sh
[root@localhost ~]# ./sum.sh 
0,5

自定义函数

#!/bin/bash
service_index(){
  echo "usage:servicectl <servicename> <start | stop | reload | restart | status>"
  return 1
}
service_version(){
  grep "release 7" /etc/centos-release &> /dev/null && echo "centos7"
  grep "release 6" /etc/centos-release &> /dev/null && echo "centos6"
}
servicectl(){
  [[ -z $1 || -z $2 ]] && service_index
  [ $(service_version) = "centos7" ] && systemctl $2 ${1}.service || service $1 $2
}
[root@localhost ~]# vim servicectl.sh
[root@localhost ~]# source servicectl.sh 
[root@localhost ~]# servicectl 
usage:servicectl <servicename> <start | stop | reload | restart | status>
unknown operation '.service'.
usage: service < option > | --status-all | [ service_name [ command | --full-restart ] ]
[root@localhost ~]# servicectl sshd status
● sshd.service - openssh server daemon
   loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
   active: active (running) since tue 2019-10-08 03:07:15 cst; 11s ago
     docs: man:sshd(8)
           man:sshd_config(5)
 main pid: 3169 (sshd)
   cgroup: /system.slice/sshd.service
           └─3169 /usr/sbin/sshd -d

oct 08 03:07:15 localhost systemd[1]: starting openssh server daemon...
oct 08 03:07:15 localhost sshd[3169]: server listening on 0.0.0.0 port 22.
oct 08 03:07:15 localhost sshd[3169]: server listening on :: port 22.
oct 08 03:07:15 localhost systemd[1]: started openssh server daemon.