Skip to content
Advertisement

Understand shell script interpreter with custom shell [closed]

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 commandn";
        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 say ,my c++ code is: interactive shell
  2. How interpreters work on shell scripts ? #!/PATH/TO/COMPILED/SHELL
  3. How can fix code or script to activate interpreting feature ?

Advertisement

Answer

  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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement