[英]How, or in which pattern, are environment variables listed in a shell (bash)?
I have a task to implement my own shell in C from scratch for my school.我有一项任务是为我的学校从头开始用 C 语言实现我自己的 shell。
As a reference, I must take bash
.作为参考,我必须拿
bash
。
My question is, how are the environ variables listed when either env
or printenv
are called?我的问题是,当调用
env
或printenv
时,如何列出环境变量?
I've noticed it's neither by creation date nor by alphabetical order.我注意到它既不是按创建日期也不是按字母顺序。
My shell has its own environment as a char **
, and I'm wondering how should I shuffle it after a new variable declared so that it imitates bash
correctly.我的 shell 有自己的环境作为
char **
,我想知道在声明一个新变量之后我应该如何对其进行洗牌,以便它正确地模仿bash
。
I tried running export a=aaaa
in bash
and it appeared in the middle of the list.我尝试在
bash
运行export a=aaaa
并且它出现在列表的中间。
how are the environ variables listed when either env or printenv are called?
调用 env 或 printenv 时如何列出环境变量?
Both these programs are open source.这两个程序都是开源的。 From coreutlis/env.c :
来自coreutlis/env.c :
char *const *e = environ;
while (*e)
printf ("%s%c", *e++, opt_nul_terminate_output ? '\0' : '\n');
From coreutils/printenv :从coreutils/printenv :
for (env = environ; *env != NULL; ++env)
printf ("%s%c", *env, opt_nul_terminate_output ? '\0' : '\n');
I've noticed it's neither by creation date nor by alphabetical order.
我注意到它既不是按创建日期也不是按字母顺序。
Inspectingglibc/setenv.c I think it appends the values on the end, and keeps a separate binary search tree ( #include <search.h>
) with variable names for fast searching.检查glibc/setenv.c我认为它会在末尾附加值,并保留一个单独的二叉搜索树(
#include <search.h>
),其中包含变量名以便快速搜索。
Posix states from https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html : Posix 状态来自https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html :
There is no meaning associated with the order of strings in the environment.
环境中字符串的顺序没有任何意义。
and I think this is enough to give implementations freedom to use any order they want.我认为这足以让实现自由使用他们想要的任何顺序。
in bash and it appeared in the middle of the list.
在 bash 中,它出现在列表的中间。
There is no reason for Bash to use environ. Bash 没有理由使用环境。 Bash has its own export_env 2d array, and it keeps variables using its own
HASH_TABLE
implementation - hashlib.c and also VAR_CONTEXT
. Bash 有自己的export_env 2d 数组,它使用自己的
HASH_TABLE
实现来保存变量 - hashlib.c和VAR_CONTEXT
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.