Shell variables in Linux

Source: Internet
Author: User
Tags echo command dsquery

To make shell programming more effective, the system provides some shell variables. Shell variables can save variable names such as pathnames, file names, or numbers. Shell regards any settings as text strings.
There are two types of variables: local and environment. Strictly speaking, there can be four types, but the other two types are read-only and can be considered as special variables, which are used to pass parameters to shell scripts.

1. What is a shell variable?
According to the definition, variables are some readable and writable storage units in the storage device. variables can be used to customize the user's work environment. You can use variables to save useful information so that the system can know user settings. Variables are also used to save Temporary Information. For example, if a variable is editor, there are many editing tools in the system. But which one is suitable for the system? Assign the editor name to the editor. In this way, when you use cron or the application whose editor is required
This is the editor value you will always use and use it as the default editor. For example, you need to edit the Logon audit system. When this option is selected in the menu, the value of the editor variable is vi. The system knows that you can use this editor (use the echo $ editor command to check your ?). In another example, You need to log on to the database system and enter the following command:
$ ISQL-udavet-pabcd-smethsys
Here-S is the name of the server being connected. There is a variable dsquery to save the server name value. Set the server name value to the dsquery variable. If you do not use-s to provide the server name when logging on, the application queries the dsquery variable and uses the value as the server name. All you need to do is to type the following command:
$ ISQL-udavet-pabcd
The work method is the same as above. 2 local variables
This local variable is used in your current shell lifecycle script. For example, the value of volume variable file-nameis loop.doc, which is valid only during the user's current shell lifecycle. This value is invalid if another process is started or exited in shell. The advantage of this method is that you cannot set this variable for other shells or processes. When using a variable, If you enclose it in curly brackets, it can prevent shell from misunderstanding the variable value. Although you do not have to do so, this is indeed available. Set a local variable in the format:
$ Variable-name = value or $ {Variable-name = value} note that there can be spaces on both sides of the equal sign. If the value contains spaces, it must be enclosed in double quotation marks. Shell variables can contain uppercase and lowercase letters. Different modes for variable setting:
Variable-name = value sets the actual value to variable-name
Variable-name + value if variable-name is set, reset its value
Variable-name :? If variable-name is not set for value, the undefined user error message is displayed.
Variable-name? If variable-name is not set for value, the system error message is displayed.
Variable-name: = value if variable-name is not set, set its value
Variable-name:-value is the same as above, but the value is not set to variable-name. It can be replaced. 2.1 display Variables
You can use the echo command to display the values of a single variable and add $ before the variable name. For example:
Echo $ LOGNAME
$ Dave
You can use the variables in combination. The following sets the error message and the environment variable LOGNAME to the variable error-msg.
$ ERROR_MSG = \ "sorry, there is not $ LOGNAME \"
$ Echo \ "$ ERROR_MSG \"
$ Sorry, there is not dave in the above example, shell first displays the text, then searches for the variable $ LOGNAME, and finally extends the variable to display the entire variable value. 2.2 clear Variables
Run the unset command to clear the variable.
Unset variable-name 2.3 display all local shell Variables
Use the set command without any parameters to display all locally defined shell variables.
The set output may be very long. When viewing the output, we can see that shell has set some user variables to make the work environment easier to use. 2.4 combine variable values
Adding variables side by side can combine variables:
Echo $ var_1 $ var_2 2.5 test whether the variable has been set
Sometimes you need to test whether a variable has been set or initialized. If it is not set or initialized, you can use another value. The command format is:
$ {Variable:-value}
That is, if a variable value is set, use it. If no value is set, the new value is obtained. For example:
$ Color = blue
$ Echo \ "the sky is $ {color:-gray} today \"
The sky is blue today
When the color value of the variable is blue and ECHO is used to print the color, first check whether the variable has been assigned a value. If yes, use this value. Clear the value now and check the result.
$ Color = blue
$ Unset color
$ Echo \ "the sky is $ {color:-gray} today \"
The sky is gray today example above does not pass the actual value to the variable, you need to use the following command to complete this function:
$ {Variable: = value} 2.6 Use variables to save System Command Parameters
You can use variables to save the replacement information of system command parameters. The following example uses a variable to save the file name information copied to a file. The source variable stores the path of the passwd file.
$ Source = \ "/etc/passwd \"
$ CD $ Source 2.7 set read-only variables
If you do not want to change the value of a variable, you can set it to read-only. If someone includes the user who wants to change it, an error message is returned. The format is as follows:
Variable-name = Value
Readonly variable-name
If it is set to read-only, any operation that changes its value will return an error message. To view all read-only variables, run the readonly command. 3. Environment Variables
Environment variables are used for all user processes (often referred to as subprocesses ). A logon process is called a parent process. User processes executed in s h e l are called sub-processes. Unlike local variables (only for current s h e l), environment variables can be used for all sub-processes, including editors, scripts, and applications.
Environment variables can be set in the command line, but these values will be lost when the user logs out, so it is best to define them in the. profile file. The system administrator may have set some environment variables in the/etc/profile file. Put it into the profile file, which means that these values will be initialized each time you log on. Traditionally, all environment variables are capitalized. Before applying environment variables to user processes, you must use the export command to export them. Environment variables are set in the same way as local variables. 3.1 set Environment Variables
VARIABLE-NAME = value; export VARIABLE-NAME
There is a semicolon between two commands, which can also be written as follows:
VARIABLE-NAME = value
Export VARIABLE-NAME 3.2 display environment variables
Use the echo command to display environment variables, just like local variables.
Use the env command to view all environment variables. 3.3 clear Environment Variables
Run the unset command to clear environment variables.
Unset VARIABLE-NAME 3.4 embed shell Variables
Brourne shell has some reserved environment variable names that cannot be used for other purposes. These embedded environment variables are usually created in/etc/profile, but not completely, depending on the user. The following is a list of embedded shell variables.
1. CDPATH
Change directory path variables and keep a series of path names separated by colons for cd commands. If you set CDPATH and cd as a directory, first find CDPATH. If CDPATH indicates this directory, this directory becomes the current working directory. Example:
$ CDPATH =:/home/dave/bin:/usr/local/apps; export CDPATH.
If you want
$ CD apps
The CD command first looks for the directory list in the cdpath. If apps are found, it becomes the current working directory.
2. exinit
The exinit variable saves the initialization options when the VI editor is used. For example, when calling VI, You need to display the row number and add the tab key to the 10th spaces. The command is:
$ Exinit = \ 'set nu tab = 10 \ '; export exinit
3. Home
Home Directory, usually located in the last 2nd columns of the passwd file, used to save your own files. If the home directory is set, run the CD command to access it. You can also use
$ CD $ home
4. Ifs
IFS is used as the default domain separator specified by shell. In principle, the domain separator can be any character, but the default is usually a space, a new line, or a tab key. IFS is useful when separating files or fields in variables. In the following example, the IFS is set to a colon, and then the echo $ PATH variable gives a list of highly readable paths separated by directories.
/Sbin/bin/usr/bin/home/Dave/bin
To set its return initial settings:
$ Ifs = <space> <tab>; export IFS
<Space> <tab> is a space and a tab key.
5. LOGNAME
If this variable is used to save the login name, it should be set by default, but if it is not set, you can use the following command to complete it:
$ LOGNAME = \ 'Dave \ '; export LOGNAME
6. Mail
The mail variable saves the mailbox path name. The default value is/var/spool/mail/<loginname>. Shell periodically checks for new emails. If there is a new email, a prompt is displayed on the command line. If the mailbox is not in the specified location, you can use mail to set it.
$ Mail =/usr/mail/Dave; export mail
7. mailcheck
Mailcheck checks new emails every 60 s by default, but if you do not want to check new emails so frequently, for example, set it to every 2 m, run the following command:
$ Mailcheck= 120; export mailcheck
8. mailpath
If mailpath is required for multiple mailboxes, this variable will overwrite the mail setting.
$ Mailpath =/var/spool/DAVE:/var/spool/admin; export mailpath
In the above example, the mail detects the mailboxes Dave and Admin.
9. Path
The PATH variable stores the directory order for command or script search. It is important to arrange the order correctly and save time during command execution. You do not want to search for a command in a directory that does not exist. In general, it is best to put it in the home directory first, followed by the sequence from the most commonly used to the list of commonly used directories. If you want to query in the current working directory, you can use periods wherever you are. Directories are separated by colons. For example:
$ Path = $ home/bin:.:/bin:/usr/bin; export path
Use the above example to first find the home/bin directory, then the current working directory, then/bin, and finally
/Usr/bin.
You can set the path in the/etc/profile directory in the system directory, or you can add your own directory by using the following method.
$ PATH = $ PATH:/$ HOME/bin:.; export PATH
Here, the PATH defined in/etc/profile is used, and $ HOME/bin and the current working directory are added. Generally, it is not a good method to start using the current working directory in the search path, which is easily discovered by other users.
10. PS1
The basic prompt contains a shell prompt. The default value is # For the super user, and the other value is $. You can use any symbol as a prompt.
11. PS2
PS2 is the affiliated prompt. The default is the symbol>. PS2 is used to execute multi-line commands or a command that exceeds one line.
12. SHELL
The SHELL variable saves the default shell, which is usually set in/etc/passwd. However, if necessary, use another shell,
You can overwrite the current shell using the following method:
13. TERMINFO
The location where the terminal initialization variable saves the terminal configuration file. Usually in/usr/lib/terminfo or/usr/share/terminfo
$ TERMINFO =/usr/lib/terminfo; export TERMINFO
14. TERM
The storage terminal type of the TERM variable. Set the TERM to let the application know the control sequence type of the terminal to the screen and keyboard response, commonly used vt100, vt200, vt220-8 and so on.
$ TERM = vt100; export TERM
15. TZ
The Time Zone variable saves the time zone value. Only the system administrator can change this setting. For example:
$ Echo $ TZ
GMT2EDT
The return value indicates that the Greenwich Mean Time is in use, and the time difference is 2 from GMT, and is saved as EDT. 3.5 Other environment variables
There are also some reserved environment variables. Other systems or command line applications will use them. The following are some of the most common values. Note that these values are not set by default and must be displayed.
1. EDITOR
Set Editor, the most common.
$ EDITOR = vi; export EDITOR
2. PWD
The path name of the current directory. Use the cd command to set this option.
3. PAGER
This function is used to save screen paging commands, such as pg and more, when viewing man text.
$ PAGER = \ 'pg-f-p % d \ '; export PAGER
4. MANPATH
Save the man text directory on the system. Directories are separated by colons.
$ MANPATH =/usr/apps/man:/usr/local/man; export MANPATH
5. LPDEST or PRINTER
Save the default printer name, which is used to specify the printer name when printing a job.
$ LPDEST = hp3si-systems 3.6 set command
When you set environment variables in the $ HOME. profile file, there is another way to export these variables. Use the set command-a option, that is, set-a indicates that all variables are exported directly. Do not use this method in/etc/profile. It is best to use it only in your $ HOME/. profile file. 3.7 export variables to sub-Processes
One of the problems new shell users encounter is how to export the Defined variables to sub-processes. We have discussed how environment variables work. Now we use scripts to implement them and call another script in the script (this actually creates a sub-process ). The following are two script lists: father and child. The father script sets the variable film. The value is AFewGoodMen, returns the variable information to the screen, and then calls the script child. This script displays the variable film in the first script, and changes the value to DieHard, then display it on the screen, and finally control the returned father script to display this variable again.
$ More father
#! /Bin/sh
# Father script
Echo \ "this is the father \"
FILM = \ "A Few Good Men \"
Echo \ "I like the film: $ FILM \"
# Call the child script
./Child
Echo \ "back to father \"
Echo \ "and the film is: $ FILM \" $ more child
#! /Bin/sh
# Child script
Echo \ "called from father .. I am the child \"
Echo \ "film is: $ FILM \"
FILM = \ "Die Hard \"
Echo \ "changing film to: $ FILM \" to check the script display result:
This is the father
I like the film: A Few Good Men
./Child: line 1: child: command not found
Called from father.. I am the child
Film is:
Changing film to: Die Hard
Back to father
And the film is: A Few Good Men because the film variable is not exported in father, the child script cannot return the film variable. If you add the export command to the father script so that the child script knows the value of the film variable, this will work:
$ More father2
#! /Bin/sh
# Father2 script
Echo \ "this is the father \"
FILM = \ "A Few Good Men \"
Echo \ "I like the film: $ FILM \"
# Call the child script
# But export varible first
Export FILM
./Child
Echo \ "back to father \"
Echo \ "and the film is: $ FILM \" $./father2.
This is the father
I like the film: A Few Good Men
Called from father.. I am the child
Film is: A Few Good Men
Changing film to: Die Hard
Back to father
And the film is: A Few Good Men because the export command is added to the script, the variable film can be used in any number of scripts, all of which inherit the ownership of film. 4. location variable parameters
At the beginning of this chapter, four variables are mentioned: local, environment, and two other variables are considered special variables because they are read-only. These two variables are location variables and specific variable parameters. Let's take a look at the location variable.
If you want to pass information to a shell script, you can use the location parameter to complete this function. The number of parameters can be input into the script. This number can be any number, but only the first nine can be accessed. You can change this limit by using the shift command (the shift command will be discussed later ). The parameter starts from the first one and ends at 9th. The $ symbol must be added before each access parameter. The first parameter is 0, indicating that the actual Script Name is reserved for storage. This value can be used regardless of whether the script has parameters.
If You send Did You See Th e Full Moon information to the script, the following table describes how to access each parameter.
$0 $1 $2 $3 $4 $5 $6 $7 $8 $9
Script Name Did You See The Full Moon 4.1 Use location parameters in scripts
Use the above example in the script below.
$ More param
#! /Bin/sh
# Param
Echo \ "This is the script name: $0 \"
Echo \ "This is the first parameter: $1 \"
Echo \ "This is the 2nd parameter: $2 \"
Echo \ "This is the third parameter: $3 \"
Echo \ "This is the 6th parameter: $6 \"
Echo \ "This is the 7th parameter: $7 \" $./param Did You See The Full Moon
This is the script name:./param
This is the first parameter: Did
This is the 2nd parameter: You
This is the third parameter: See
This is the 6th parameter: Moon
This is the 7th parameter: only six parameters are passed here. the 7, 8, and 9 parameters are null, as expected. Note: The first parameter indicates the script name. This parameter is useful when error messages are disposed of from the script. Note: $0 returns the current directory path. If only the Script Name is returned, set the parameter to $0 under the basename command to get the script name.
$ More param2
#! /Bin/sh
Echo \ "this is 'basename $ 0' calling \" $./param2
This is param2 calling 4.2 PASS Parameters to system commands
You can pass parameters to system commands in a script. In the following example, use the $1 parameter in the find command to specify the file name to be searched.
$ More findfile
#! /Bin/sh
# Findfile
Find/-name $1-print in another example, use $1 to pass a user ID number to grep, and grep uses this ID number to search for the user's full name in passwd.
$ More who_is
#! /Bin/sh
# Who_is
Grep $1 passwd | awk-F: {print $4} 4.3 specific variable parameters
Now that you know how to access and use the parameters in shell scripts, it is useful to know more about the relevant information. It is necessary to know some related control information during script running, this is the origin of specific variables. There are 7 specific variables: $ # number of parameters passed to the script
$ * Display all parameters passed to the script with a single string. Different from location variables, this option can have more than 9 Parameters
$ ID of the current process running the script
$! ID of the last process running in the background
$ @ Is the same as $ #, but it is enclosed by quotation marks and each parameter is returned in quotation marks.
$-Display the current options used by shell, which have the same functions as the set command.
$? Displays the exit status of the last command. 0 indicates no error, and any other value indicates an error. The output of specific variables gives you more information about scripts. You can check the number of parameters passed and the ID of the process to avoid killing the process. 4.4 final exit status
Note: $? Returns 0. You can return this variable in any command or script to obtain the returned information. Based on this information, you can perform further research in the script. Returning 0 means success, and 1 indicates an error.
In the following example, copy the file to/tmp and use $? Check results.
$ CP OK .txt/tmp
$ Echo $?
0. Try to upload a file to a non-existent directory:
$ CP OK .txt/usr/bin/AAA/BBB
CP: cannot create regular file \ '/usr/bin/AAA/BBB \': no such file or directory
$ Echo $?
1 use $? Check the returned status. We can see that the script has an error, but we also find CP: cannot.... Therefore, it is unnecessary to check the final exit status. In the script, you can use system commands to process the output format. The command output is not displayed on the screen. Therefore, the output can be redirected to/dev/null, that is, the system bin. How can I know whether the script is correct? Okay. Now you can use the exit command. See the actual operation results in this form in the previous example.
$ CP OK .txt/usr/bin/AAA/BBB>/dev/null 2> & 1
$ Echo $?
1. By redirecting the output containing the error information to the system bin, you cannot know the returned status of the last command, but you can use $ !, (The return value is 1) the script fails. When checking the exit status of a script, it is best to set the return value to a meaningful name to increase the readability of the script. Conclusion 4.5
Variables make shell programming easier. It can save input values and improve efficiency. Shell variables can contain almost any
Value. Specific variables enhance the script function and provide more information about the parameters passed to the script.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.