Answers:
如果脚本/path/to/foo以开头#!/bin/bash,则执行/path/to/foo arg1 arg2等同于执行/bin/bash /path/too/foo arg1 arg2。如果shebang行是#!/bin/bash -ex,则等效于执行/bin/bash -ex /path/too/foo arg1 arg2。此功能由内核管理。
请注意,在shebang行上您只能移植一个参数:某些unices(例如Linux)仅接受一个参数,因此这#!/bin/bash -e -x将导致bash接收单个五个字符的参数-e -x(语法错误),而不是两个参数-eand -x。
对于Bourne Shell sh和派生Shell(例如POSIX sh,bash,ksh和zsh):
-e 表示如果任何命令失败(通过返回非零状态表示),脚本将立即终止。-x 使外壳程序打印执行跟踪。其他程序可能会理解这些选项,但含义不同。
它们是传递给您的选项,以bash查看help set更多信息,在这种情况下:
-x Print commands and their arguments as they are executed.
-e Exit immediately if a command exits with a non-zero status.
-ex同时做两
man bash)In addition to the single-character shell options documented in the description of the set builtin command, bash interprets the following options when it is invoked: [...]。
我只想提及一种更好的方法(如便携式方法):
#!/usr/bin/env bash
上面的示例env用于查找bash可执行文件,该可执行文件并不总是位于/bin/bash。例如,老式#!/bin/bash脚本在NixOS上不起作用。
如果env按照上面的说明使用,就无法提供诸如-eto 的参数bash(据我所知)。但是您可以改为:
#!/usr/bin/env bash
set -e
env尤其是对于运行python的脚本,用法并不理想,因为您根本不知道默认python版本是2还是3,因此对于需要特定版本的脚本而言,差异很大。明确而不是狡猾