diff --git a/2.Linux Shell 脚本编程最佳实践.md b/2.Linux Shell 脚本编程最佳实践.md index 49f14c5..d54e14c 100644 --- a/2.Linux Shell 脚本编程最佳实践.md +++ b/2.Linux Shell 脚本编程最佳实践.md @@ -1,5 +1,4 @@ - ## 前言 @@ -35,6 +34,39 @@ ## 用什么样的 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 + +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