在简单的linux shell中实现环境变量
我要在linux中编写一个简单的shell,它可以实现包括环境变量在内的各种功能。我尝试使用 getenv 打印这些变量,但遇到了一些问题。即使用户输入正确的变量(例如 $HOME
),getenv
也始终返回 NULL
。这是我的代码
int i = 0;
if(strcmp(cmdArgv[i], "echo") == 0){
char *variable;
for(i = 1; cmdArgv[i] != NULL; i++){
variable = getenv(cmdArgv[i]);
if(!variable){
puts("not a variable");
printf("%s ", cmdArgv[i]);
}else{
puts("a variable");
printf("%s ", variable);
}
}
printf("\n");
exit(0);
}
,它不会进入 else
条件。例如,如果用户输入 echo ls $HOME
。此输入被解析为 cmdArgv
,它是一个 char **
。那么我的输出是
not a variable
ls
not a variable
$HOME
BUT $HOME
是一个变量,所以也许我的 getenv
实现不正确。对于问题所在有什么想法吗?谢谢。
I am to program a simple shell in linux that can implement various stuffs including environment variables. I tried printing these variables using getenv
but I have some problems. getenv
always return NULL
even if the user types a correct variable like $HOME
for example. Here is my code
int i = 0;
if(strcmp(cmdArgv[i], "echo") == 0){
char *variable;
for(i = 1; cmdArgv[i] != NULL; i++){
variable = getenv(cmdArgv[i]);
if(!variable){
puts("not a variable");
printf("%s ", cmdArgv[i]);
}else{
puts("a variable");
printf("%s ", variable);
}
}
printf("\n");
exit(0);
}
It doesn't enter into the else
condition. For example if the user types echo ls $HOME
. This input is parsed into the cmdArgv
which is a char **
. Then the output I have is
not a variable
ls
not a variable
$HOME
BUT $HOME
is a variable so maybe my implementation of getenv
isn't right. Any ideas as to what seem to be the problem? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该变量称为
HOME
,而不是$HOME
。 (后者是 shell 用于扩展变量的语法。)The variable is called
HOME
, not$HOME
. (The latter is your shell's syntax for expanding the variable.)