Quote:
Originally Posted by supasoaker
Hi all,
Bash commands have been outlined to me as follows:
Command Options Arguments
My question is, how is this implemented in the source code? Is a command a function that is called for example? Or is it done some other way?
Any examples to hand?
Thanks in advance for any help! I am simply trying to understand better the mechanics of what happens when I type a command.
|
Part 1 is the command shell interpreter (bash/csh/tcsh/...) interacts with the parameter.
Technically, all applications receive two items of information at the main program initiation (as in the following code)
Code:
#include <stido.h> /*standard I/O library*/
#include <stdlib.h> /* some utility functions that might get used*/
/* the normal main program entry (it is possible to forces something else, but doing so is a pain,
and non-standard */
int main(int argc, /* the number of parameters */
char **argv) /* pointer to a list of pointers to the parameters */
{
int i;
for (i = 0; i < argc; i++) {
printf("parameter %d = %s\n",i,argv[i]);
}
return(0); /* even the main is a function... 0 implies no errors were detected */
}
The above program should print all the parameters - the same function that the "echo" command does.
As illustrated, how the parameters are used is up to the program. By convention (in other words, historical), program options are identified by strings that start with a '-' character.
Some applications DON'T follow this convention - one notable one is the dd utility (data dump originally)
The dd utility interprets all the parameters as a "name=value" list, so the program itself does that.
Other programs (more conventional) use a library function "getopt" which will do most of the work, and allow the program to use a simple switch code block to interpret the options.
Still other programs will mix options and parameters - using things like -f for the option, which indicates the following parameter is a file. In the basic form this is also handled by the getopt library, any options remaining after it has finished evaluation have to handled manually (though they could just be ignored, a perfectly valid thing to do).