- Location parameters
- Internal Parameters
Just as the LS command can accept directories and other parameters as its parameters, parameters can also be used in shell programming. Parameters in Shell programs include location parameters and internal parameters.
3.1 Location Parameters
The parameter provided by the system is calledLocation parameters. The value of the location parameter can be used$ NN is a number. If n is 1, it is $1. Similar to the array in C language, Linux segments the input command string and marks each segment. The label starts from 0. The value 0th is the program name. It indicates the parameter passed to the program from 1. For example, $0 indicates the program name, $1 indicates the first parameter passed to the program, and so on.
3.2 Internal Parameters
In the above process, $0 is an internal variable, which is mandatory, while $1 is dispensable. The most common internal variables include $0, $ #, $? And $ *. Their meanings are as follows.
- $0: the path where the command contains the command.
- $ #: The total number of parameters passed to the program.
- $? : When the shell program exits in the shell, 0 is returned for normal exit, and the non-0 value is returned.
- $ *: A string consisting of all parameters passed to the program.
Example 2: compile a shell program to describe the location parameters in the shell program: $0, $ #, $? , $ *, The program name is test1, the Code is as follows:
[[Email protected] bin] # vi test1
#! /Bin/sh
Echo "program name is $0 ";
Echo "there are totally $ # parameters passed to this program ";
Echo "the last is $? ";
Echo "the parameter are $ *";
The execution result is as follows:
[[Email protected] bin] # test1 this is a test program // pass 5 parameters
Program name is/bin/test1 // give the complete path and name of the program
There are totally 5 parameters passed to this program // The total number of parameters
The last is 0 // program execution result
The parameters are this is a test program // returns a string composed of parameters
Note: The command is not included in the parameter.
Example 3: Use internal variables and location parameters to compile a simple deletion program named Test2. For example, if the file name to be deleted is A, the command entered in the terminal is: Test
Analysis: in addition to the command, there is at least one location parameter, that is, $ # cannot be 0, and deletion cannot be $1. The program design process is as follows.
(1) Use VI to edit the program
[[Email protected] bin] # vi Test2
#! /Bin/sh
If test $ #-EQ 0
Then
Echo "Please specify a file! "
Else
Gzip $1 // compress the file
MV upload 1.gz $ home/dustbin // move to the recycle bin
Echo "File $1 is deleted! "
Fi
(2) Set permissions
[[Email protected] bin] # chmod + x Test2
(3) Run
[[Email protected] bin] # Test2 A (if file a exists in the bin directory)
File a is deleted!