Bob
Bob

Reputation: 23

How can I get the local shell variables in C?

I'm currently working on my own replica of the history builtin. I realize I need the HISTSIZE, HISTFILE and HISTFILESIZE variables to achieve the command options but I don't know how to get them. Is there a function similar to getenv or a variable like environ but with the local shell variables ?

Thanks in advance !

Upvotes: 2

Views: 3762

Answers (4)

Serge Ballesta
Serge Ballesta

Reputation: 148900

Well a builtin is executed directly by the shell for 2 possible reasons:

  • you avoid spawning a new processus (performance reason)
  • it is the only way to have access to internal shell variables (your use case)

A shell could only provide access to its internal variables by two ways:

  • either copy them to the environment because by definition the environment is the list of variables that are passed to child processes
  • either provided an inter process communication mechanism (named pipe, private sockect, etc.) to allow its childs to ask them

AFAIK, no common shell implement either, but you can export the required shell variables to the environment:

export HIST
export HISTSIZE
export HISTFILESIZE

should be enough to later get them through getenv

Upvotes: 2

muXXmit2X
muXXmit2X

Reputation: 2765

As Steffan Hegny pointed out, there is no way to acces these variables if they are no environment variables. So popen(), what I thought could help, isn't a solution to your problem.

However if you need acces to those variables you can export their values to a real environment variable which can be accessed via getenv(char*).

E.g.

export _HISTFILE=$HISTFILE && ./myProgram

or

_HISTFILE=$HISTFILE ./myProgram

with myProgram accessing the value like this:

#include <stdio.h>
#include <stdlib.h>

int main() 
{
  printf("History file: %s", getenv("_HISTFILE"));
}

Upvotes: 0

Sumit Gemini
Sumit Gemini

Reputation: 1836

#include <stdio.h>
#include <stdlib.h>

int main() {

printf("SET = %s\n",getenv("SET"));

return 0;

}

To test Program, set the variable first and then execute :-

export SET=1

Upvotes: 0

Thomas Blanquet
Thomas Blanquet

Reputation: 507

The main declaration can have an extra argument, char **envp, which is an 2D array of char terminated by a NULL pointer. Here is an example :

#include <stdio.h>

int main(int argc, char **argv, char **envp)
{
   int index = 0;
   while (envp[index])
       printf("%s\n", envp[index++];
   return 0;
}


EDIT


Using envp will provide you to get the environnement. To find shell variables, I found this. I think that could help you.

Upvotes: 1

Related Questions