Skip to main content
Linux command-line arguments and shell environment
deep5
linux Command-Line Arguments and Shell Environment
When a user types a command, the program that is loaded to satisfy the request may
receive some command-line arguments from the shell. For example, when a user
types the command:
$ ls -l /usr/bin
to get a full listing of the files in the /usr/bin directory, the shell process creates a new
process to execute the command. This new process loads the /bin/ls executable file.
In doing so, most of the execution context inherited from the shell is lost, but the
three separate arguments ls, -l, and /usr/bin are kept. Generally, the new process
may receive any number of arguments.
The conventions for passing the command-line arguments depend on the high-level
language used. In the C language, the main( ) function of a program may receive as
its parameters an integer specifying how many arguments have been passed to the
program and the address of an array of pointers to strings. The following prototype
formalizes this standard:
int main(int argc, char *argv[])
Going back to the previous example, when the /bin/ls program is invoked, argc has
the value 3, argv[0] points to the ls string, argv[1] points to the -l string, and
argv[2] points to the /usr/bin string. The end of the argv array is always marked by
a null pointer, so argv[3] contains NULL.
A third optional parameter that may be passed in the C language to the main( ) func-
tion is the parameter containing environment variables. They are used to customize the
execution context of a process, to provide general information to a user or other pro-
cesses, or to allow a process to keep some information across an execve( ) system call.
To use the environment variables, main( ) can be declared as follows:
int main(int argc, char *argv[], char *envp[])
The envp parameter points to an array of pointers to environment strings of the form:
VAR_NAME=something
where VAR_NAME represents the name of an environment variable, while the substring
following the = delimiter represents the actual value assigned to the variable. The end
of the envp array is marked by a null pointer, like the argv array. The address of the
envp array is also stored in the environ global variable of the C library.
Command-line arguments and environment strings are placed on the User Mode
stack, right before the return address (see the section “Parameter Passing” in