How to access a shell variable from one context in another shell context

I ran the following shell command

sw0:root> pwd
/root
sw0:root> echo $(history 1)
2 echo $(history 1)
sw0:root>

      

Now I am calling the system syscall in the c file as shown below

system (" echo \"___history1 = $(history 1)____\"");

      

Output:

___history1 = ____

      

What I have tried, I am trying to read the last shell history command from C using a system call system

.

Clarify the following doubts.

  • Why can't I read the last history command executed in shell from c file?

  • Is it because when I call the syscall it forks the new shell?

  • If so, how can I achieve this? Reading command output 1 shell from another?

+3


source to share


2 answers


When you run your program, it runs in a subshell and does not inherit the history of the calling shell.



You can compare it to running bash -c history

, you won't get results.

0


source


You open a shell: 1 is now executing some commands. Now close this shell.

After that open a new shell2 and use the command system()

, it will have information about the commands executed in shell1


Until you close the current shell, its history is not dumped into the global history file.

Yes, the system will open its own context.




OP: I ran this command in the main shell which is started from boot the system, so is there a way I could manually clear it?

To do this, you need to add this line to your .bashrc file

export PROMPT_COMMAND='history -a'

      

see http://www.aloop.org/2012/01/19/flush-commands-to-bash-history-immediately/

0


source







All Articles