作为一个运维人员编写Shell脚本是很平常的,一个格式好的脚本不仅赏心悦目,后期自己和别人也易于维护。
下面的脚本就是我自己的shell编写格式,如下:
1 [root@mini05 20180930-2]# cat template.sh
2 #!/bin/sh
3 ################ Version Info ##################
4 # Create Date: 2018-09-29
5 # Author: Zhang
6 # Mail: zhang@xxxx.com
7 # Version: 1.0
8 # Attention: shell脚本模板
9 ################################################
10
11 # 加载环境变量
12 # 如果脚本放到crontab中执行,会缺少环境变量,所以需要添加以下3行
13 . /etc/profile
14 . ~/.bash_profile
15 . /etc/bashrc
16
17 # 脚本所在目录即脚本名称
18 script_dir=$( cd "$( dirname "$0" )" && pwd )
19 script_name=$(basename ${0})
20 # 日志目录
21 log_dir="${script_dir}/log"
22 [ ! -d ${log_dir} ] && {
23 mkdir -p ${log_dir}
24 }
25
26 errorMsg(){
27 echo "USAGE:$0 arg1 arg2 arg3"
28 exit 2
29 }
30
31
32 doCode() {
33 echo $1
34 echo $2
35 echo $3
36 }
37
38 main() {
39 if [ $# -ne 3 ];then
40 errorMsg
41 fi
42 doCode "$1" "$2" "$3"
43 }
44
45 # 需要把隐号加上,不然传入的参数就不能有空格
46 main "$@"
测试如下:
1 [root@mini05 20180930-2]# ./template.sh
2 USAGE:./template.sh arg1 arg2 arg3
3 [root@mini05 20180930-2]# ./template.sh 111
4 USAGE:./template.sh arg1 arg2 arg3
5 [root@mini05 20180930-2]# ./template.sh 111 '222 333'
6 USAGE:./template.sh arg1 arg2 arg3
7 [root@mini05 20180930-2]# ./template.sh 111 '222 333' "444 555"
8 111
9 222 333
10 444 555
11 [root@mini05 20180930-2]# ./template.sh 111 '222 333' "444 555" "666"
12 USAGE:./template.sh arg1 arg2 arg3
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有