Shell 编程 函数

Posted llife

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

以上是关于Shell 编程 函数的主要内容,如果未能解决你的问题,请参考以下文章

shell 编程之函数

45shell编程-函数

Shell编程之函数

shell编程-如何定义函数如何调用函数如何调试shell

Shell编程之函数

运维linux shell 编程之函数使用