shell (bash) 中如何或以何种模式列出环境变量?

How, or in which pattern, are environment variables listed in a shell (bash)?

我有一项任务是为我的学校从头开始用 C 实现我自己的 shell。

作为参考,我一定要取bash

我的问题是,调用 envprintenv 时,如何列出环境变量?

我注意到它既不按创建日期也不按字母顺序排列。

我的 shell 有自己的环境作为 char **,我想知道在声明一个新变量后我应该如何调整它以便它正确地模仿 bash

我在 bash 中尝试了 运行 export a=aaaa,它出现在列表的中间。

how are the environ variables listed when either env or printenv are called?

这两个程序都是开源的。来自 coreutlis/env.c:

  char *const *e = environ;
  while (*e)
    printf ("%s%c", *e++, opt_nul_terminate_output ? '[=10=]' : '\n');

来自 coreutils/printenv:

  for (env = environ; *env != NULL; ++env)
    printf ("%s%c", *env, opt_nul_terminate_output ? '[=11=]' : '\n');

I've noticed it's neither by creation date nor by alphabetical order.

检查 glibc/setenv.c 我认为它会在末尾附加值,并保留一个单独的二叉搜索树 (#include <search.h>),其中包含用于快速搜索的变量名。

Posix 来自 https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html 的状态:

There is no meaning associated with the order of strings in the environment.

我认为这足以让实现自由使用他们想要的任何顺序。

in bash and it appeared in the middle of the list.

Bash 没有理由使用 environ。 Bash 有自己的 export_env 2d array, and it keeps variables using its own HASH_TABLE implementation - hashlib.c 也有 VAR_CONTEXT.