1

I'm writing a C program to run in Linux shell. Now I got a problem with such command.

#include <stdio.h>
void main()
{
char* command="history>>history";
system(command);
}

I want it to write the result of command "history" into a document, but it failed with a blank one.

If I change it to "date>>history", current system time will be written into the document.

Is there any problem with "history>>history"? What should I do if I want to get that work? Thanks!

5
  • 1
    What exactly do you want it to do here? Commented Aug 4, 2013 at 20:13
  • 1
    run which history and observe that it is... probably a shell builtin Commented Aug 4, 2013 at 20:14
  • if date writes to history, then maybe history doesn't write anything to stdout so you can redirect it with >> to a file, Commented Aug 4, 2013 at 20:16
  • Sorry, I want it to save the result of "history" to a document names "history". Commented Aug 4, 2013 at 20:16
  • is there a reason why you're using C for this, rather than a bash function? Commented Aug 4, 2013 at 20:43

1 Answer 1

5

The problem is that history is not a real command but a shell builtin. Thus you can't call it from a C program[1].

Depending on the shell the user is using, you can instead get the history from ~/.bash_history, ~/.zsh_history and so on. Note however that zsh only write to this file at the end of a session.

[1] Well, you could theorically try system("bash -c history"), but you won't get the actual history because the builtin isn't run in the context of the current session.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for figuring out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.