سؤال

I'm trying to implement a linux shell and in this part I'm trying to repeat the recent used commands. Here a sample from the code

if(strcmp(arg[0],"!") == 0 && arg[1] != NULL){
            if(strcmp(arg[1], "-1") == 0){
                 system("!!");


            }

I want the last command to execute when the user enters "! -1" I tried the system command "!!" but i got an error "command not found". Can you help please?

Thanks in advance

هل كانت مفيدة؟

المحلول

That is because !! is not really a command. It is a shortcut in bash to repeat the last recently used command. What's happening is that system is looking for !! binary file in your PATH environment variable and of course, failing to find it.

What you can do is what most shells do, keep a file of last used commands and execute the last one issued.

For example, take a look at the file ~/.bash_history. That's the command history the console keeps track of for your user. In order to achieve what you want either you store the commands in a buffer in memory (not a very good idea because if you reset or close the shell you'll lose the history) or have them in a .bash_history-like file.

Also, take a look at the history command and mostly its manual page (man history). You'll find a section PROGRAMMING WITH HISTORY FUNCTIONS that you might find useful. By including <readline/history.h> you'll get access to some functions that operates on the history. I don't know if you can use it, because this might be only accessible within bash and since you're creating your own shell, maybe it won't work. I still think that keeping track of the history yourself is a way of KISS :)

Hope this helps!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top