如何在将由 Bash 运行的脚本的 shebang (#!) 中设置环境变量?

Fre*_*nan 4 unix bash

或者,为什么这不起作用,假设您正确地将文件设置为可执行文件?(在我的系统上它只是挂起,但可以用 ^C 杀死。)

#!/usr/bin/env TEST=TEST python
print('hello')
Run Code Online (Sandbox Code Playgroud)

虽然这样做:

#!/usr/bin/env python
print('hello')
Run Code Online (Sandbox Code Playgroud)

就像这样:

[fred@pc build]$ /usr/bin/env TEST=TEST python hello.py 
hello
Run Code Online (Sandbox Code Playgroud)

小智 7

由于版本 8.30 env 有选项 -S,这使得在 Linux 中也可以工作:

使用

#!/usr/bin/env -S TEST=TEST python
Run Code Online (Sandbox Code Playgroud)


pjh*_*pjh 5

在某些系统上,包括 Linux,

#!/usr/bin/env TEST=TEST python
Run Code Online (Sandbox Code Playgroud)

'hello.py' 中的行,如果你用 './hello.py' 运行它与运行相同

/usr/bin/env 'TEST=TEST python' ./hello.py
Run Code Online (Sandbox Code Playgroud)

请注意,'TEST=TEST python' 都是一个参数。这会导致 'env' 将TEST环境变量设置为'TEST python',然后./hello.py使用exec运行。然后再次处理shebang行,并递归重复该过程。总体效果是env一遍又一遍地执行,直到过程中断。如果您在执行过程中top在系统上运行,您会看到一个非常繁忙的进程。

有关该机制如何工作的信息,请参阅Shebang (Unix)维基百科文章#!。它包括在不同系统上处理方式之间差异的一些细节。

在 Linux 和许多其他系统上的 shebang 行上设置环境变量是不可能的。您需要在程序本身中设置它们,或者,如果这不合适,则使用包装程序(例如,一个简单的 shell 程序)来运行 Python 程序。