加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Shell脚本常用模板

发布时间:2020-12-15 23:25:03 所属栏目:安全 来源:网络整理
导读:? 作为一个运维人员编写Shell脚本是很平常的,一个格式好的脚本不仅赏心悦目,后期自己和别人也易于维护。 下面的脚本就是我自己的shell编写格式,如下: 1 [[email?protected] 20180930 - 2 ]# cat template. sh 2 #!/bin/ sh 3 ################ Version I

?

  作为一个运维人员编写Shell脚本是很平常的,一个格式好的脚本不仅赏心悦目,后期自己和别人也易于维护。

  下面的脚本就是我自己的shell编写格式,如下:

 1 [[email?protected] 20180930-2]# cat template.sh 
 2 #!/bin/sh
 3 ################ Version Info ##################
 4 # Create Date: 2018-09-29
 5 # Author:      Zhang
 6 # Mail:        [email?protected]
 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 "[email?protected]"

?

测试如下:

 1 [[email?protected] 20180930-2]# ./template.sh 
 2 USAGE:./template.sh arg1 arg2 arg3
 3 [[email?protected] 20180930-2]# ./template.sh 111
 4 USAGE:./template.sh arg1 arg2 arg3
 5 [[email?protected] 20180930-2]# ./template.sh 111 222 333
 6 USAGE:./template.sh arg1 arg2 arg3
 7 [[email?protected] 20180930-2]# ./template.sh 111 222 333 "444 555"
 8 111
 9 222 333
10 444 555
11 [[email?protected] 20180930-2]# ./template.sh 111 222 333 "444 555" "666"
12 USAGE:./template.sh arg1 arg2 arg3

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读