Understand shell script interpreter with custom shell

Issue

I try to understood how shell script interpreter working.
for example i wrote custom shell with c++ :

#include <iostream>
#include <string>

using namespace std ;

int main()
{
    string input;
    while (1)
    {
        cout << "prompt:> ";
        cin >> input;
        if(input=="exit")
            return 0;
        else if(input=="test")
            cout << "You executed test command\n";
        else
            cout << "Unknown command.\n";
    }
}

now i wrote a script like this :

#!/PATH/TO/COMPILED/SHELL 
test
wrong_command1 
wrong_command2
exit    

Actually this script not working and i want to understand what part of my thinking is wrong .
Note: I executed this script on /bin/bash shell .

  1. can i call to my c++ code: interactive shell
  2. How interpreters work on shell scripts ? #!/PATH/TO/COMPILED/SHELL
  3. How can fix code or script to activate interpreting feature ?

Solution

  1. No idea what that means

  2. If you compile your program to /tmp/a.out and have an executable file script with:

    #!/tmp/a.out
    test
    wrong_command1 
    wrong_command2
    exit  
    

    which you invoke on command line as ./script then the shell running the command line will invoke /tmp/a.out ./script. I.e. looks at the shebang, invokes that command and passes the script as its first argument. The rest is up to that command.

  3. There is no interpreting feature in C++, you have to write it yourself, what you have is a good start except you need to read from the passed file argument, not stdin. Also std::getline might come handy.

Answered By – Quimby

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published