getopts 如何设置 bash 变量

How getopts is setting a bash variable

我想重新实现我自己的 getopts(如果可能,在 python 中)。

我的问题是我不明白这是怎么可能的:

# The call of the following script
./script -h

#!/bin/bash

getopts 'h' TEST # output nothing
echo $TEST # output h
env | grep # output nothing

我们在 Internet 上了解到您不能在父进程中设置变量。但这是在这里完成的,没有导出。

我想了解它是如何工作的,因为我想在 python 中做大致相同的事情。所以我的第二个问题是,是否可以在 python 中做同样的事情?

非常感谢! :)

getopts 是一个 bash 内置函数。由于它在 shell 进程中运行,因此欢迎随意更改 shell 变量。