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 .
- can i say ,my c++ code is:
interactive shell
- How interpreters work on shell scripts ?
#!/PATH/TO/COMPILED/SHELL
- How can fix code or script to activate interpreting feature ?
Advertisement
Answer
No idea what that means
If you compile your program to
/tmp/a.out
and have an executable filescript
with:JavaScript#!/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.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.