本篇主要写一些shell
脚本函数的使用。
函数调用
#!/bin/bash
sum(){
s=`expr 2 + 3`
echo $s
}
sum
[[email protected] ~]# vim sum.sh
[[email protected] ~]# chmod +x sum.sh
[[email protected] ~]# ./sum.sh
5
传递参数
#!/bin/bash
sum(){
s=`expr $1 + $2`
echo $s
}
sum 2 3
[[email protected] ~]# vim sum.sh
[[email protected] ~]# ./sum.sh
5
return
#!/bin/bash
sum(){
return $(($1 + $2))
}
sum 2 3
echo $?
[[email protected] ~]# vim sum.sh
[[email protected] ~]# ./sum.sh
5
echo
#!/bin/bash
sum(){
echo $(($1 + $2))
}
res=$(sum 2 3)
echo $?,$res
[[email protected] ~]# vim sum.sh
[[email protected] ~]# ./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
}
[[email protected] ~]# vim servicectl.sh
[[email protected] ~]# source servicectl.sh
[[email protected] ~]# servicectl
Usage:servicectl <ServiceName> <start | stop | reload | restart | status>
Unknown operation '.service'.
Usage: service < option > | --status-all | [ service_name [ command | --full-restart ] ]
[[email protected] ~]# 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.
原文地址:https://www.cnblogs.com/llife/p/11633416.html
时间: 2024-10-11 12:43:49