安全的shell最好这么写开头
#!/bin/bash
set -euxo pipefail
参数的具体含义可以用命令行 bash -c "help set" 来查看,下面是部分节选。
-x Print commands and their arguments as they are executed.
-e Exit immediately if a command exits with a non-zero status.
-u Treat unset variables as an error when substituting.
-o option-name
pipefail the return value of a pipeline is the status of
the last command to exit with a non-zero status,
or zero if no command exited with a non-zero status
翻译一遍:
e
错误就退出
x
打印执行语句
u
变量没定义就报错
-o pipefail
解决pipeline的报错问题。
涉及到的知识点
Shebang (也称为Hashbang)是一个由井号和叹号构成的字符串行(#!), 其出现在文本文件的第一行的前两个字符. 在文件中存在Shebang的情况下, 类Unix操作系统的程序载入器会分析Shebang后的内容, 将这些内容作为解释器指令, 并调用该指令, 并将载有Shebang的文件路径作为该解释器的参数.
例如, 以指令#!/bin/sh开头的文件在执行时会实际调用/bin/sh程序。
If a script /path/to/foo begins with #!/bin/bash, then executing /path/to/foo arg1 arg2 is equivalent to executing /bin/bash /path/too/foo arg1 arg2.
If the shebang line is #!/bin/bash -ex, it is equivalent to executing /bin/bash -ex /path/too/foo arg1 arg2. This feature is managed by the kernel.
网友评论