Files
team-work/2.Linux Shell 脚本编程最佳实践.md

85 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 前言
## 为什么要有规范
编码规范对于程序员而言尤为重要,有以下几个原因:
- 一个软件的生命周期中80%的花费在于维护
- 几乎没有任何一个软件,在其整个生命周期中,均由最初的开发人员来维护
- 编码规范可以改善软件的可读性,可以让程序员尽快而彻底地理解新的代码
- 如果你将源码作为产品发布,就需要确任它是否被很好的打包并且清晰无误,一如你已构建的其它任何产品
## 编码规范原则
本文档中的准则致力于最大限度达到以下原则:
- 正确性
- 可读性
- 可维护性
- 可调试性
- 一致性
- 美观
尽管本文档涵盖了许多基础知识,但应注意的是,没有编码规范可以为我们回答所有问题,开发人员始终需要再编写完代码后,对上述原则做出正确的判断。
## 用什么样的 SHELL
BASH 应该是唯一的 SHELL 脚本解释器。**因为绝大多数GNU/Linux默认安装的Shell都是bash考虑到可移植性。SHELL脚本一般用BASH解释器来执行。**
对于 `#!/bin/bash` ,大多数写过脚本的人都知道,这是命令解释器的声明,通常位于脚本的第一行,它有个专业的名字,叫做 `shebang` ,作为对命令解释器的声明,`#!/bin/bash` 声明了 bash 程序所在的路径。
有了命令解释器的路径声明,那么当执行该脚本时,系统就知道该去哪里找这个命令解释器,也就是 Shebang 中指定的 bash 。
同理,`#!/bin/sh` 也是一样的,包括非 Shell 脚本,如 `#!/usr/bin/python` 也是同理,都是声明命令解释器的位置。
```
[opc@instance-20210621-0038 ~]$
[opc@instance-20210621-0038 ~]$ ls -al /bin/bash
-rwxr-xr-x. 1 root root 964536 Nov 22 2019 /bin/bash
[opc@instance-20210621-0038 ~]$
[opc@instance-20210621-0038 ~]$
[opc@instance-20210621-0038 ~]$ /bin/bash --version
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
[opc@instance-20210621-0038 ~]$
[opc@instance-20210621-0038 ~]$ ls -al /bin/sh
lrwxrwxrwx. 1 root root 4 May 13 2021 /bin/sh -> bash
[opc@instance-20210621-0038 ~]$
```
`#!/usr/bin/env bash` ,网上经常可以看到还有这种 `shebang` 写法
> env 命令用于显示系统中已存在的环境变量,以及在定义的环境中执行指令
这种 `shebang` 写法的原理是:**当你执行 env bash 时它其实会去操作系统的PATH环境变量的路径中去查找bash可执行文件。**
## 什么时候用 SHELL
# 源文件
## 文件名称和文件编码
## SUID/SGID