版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq3399013670/article/details/86585171
1、shell脚本的建立和执行
- 脚本开头(第一行) sh是bash的软链接,推荐bash
#!/bin/bash 或#!/bin/sh
bash -version 查看版本
- 执行脚本
bash test.sh
./test.sh
. test.sh 或source test.sh #可以调用函数库
- 脚本注释(跟在#号后面的表示注释)。
当shell脚本以非交互的方式运行时,它会先查找环境变量ENV,该变量指定了一个环境文件(通常是bashrc,./bash_profile,/etc/bashrc,/ect/profile等),然后从该环境变量文件开始执行,当读取了ENV文件后,SHELL才开始执行shell脚本中的内容。
chmod u+x script_name 或chmod 755 script_name。#赋予权限
demo1:
[root@jackroo day1]# cat clear_log.sh
#!bin/bash
#清除日志脚本
LOG_DIR=/var/log
ROOT_UID=0 #$UID为0的时候,用户才具有root用户的权限
#要使用root用户来运行
if [ "$UID" -ne "$ROOT_UID" ]
then
echo "Must be root to run this script"
exit 1
fi
cd $LOG_DIR ||{
echo "Cannot change to necessary directory" >&2
exit 1
}
cat /dev/null > messages && echo "Logs cleaned up."
exit 0
# 退出之前返回0表示成功,返回1表示失败。
demo2:
[root@jackroo day1]# sh function.sh
oldboy is a teacher [确定]
[root@jackroo day1]#
[root@jackroo day1]# cat function.sh
#!bin/bash
source /etc/init.d/functions
action "oldboy is a teacher" /bin/true
2、shell脚本开发基本规范及习惯
-
开头指定脚本解释器
#!bin/sh或#!/bin/bash -
开头加版权等信息
#Date: 16:20 2012-02-12
#Author: Cratted by use01
#Mail: [email protected]
#Function: use infomation
#Version: 1.0
提示:可配置vim编辑文件时候自动加上以上信息,方法是修改~/.bimrc配置文件。 -
脚本中不用中文注释
尽量用英文注释,防止本机或切换系统环境后中文乱码的困扰。 -
脚本以sh为扩展名。
-
代码书写优秀习惯
1)成对内容的一次写出来,防止遗漏;
2)[]中括号,两边都要有空格;
3)流程控制语句一次性写完,在添加内容,如:
if 语句格式一次完成:
if 条件内容
then
a内容
fi
for循环格式一次完成:
for
do
内容
done
4)通过缩进让代码易读;