Shell variable details

Source: Internet
Author: User

1 shell variable Basics
Shell variables are very "weak" variables. By default, a variable stores a string, and shell does not care about the meaning of the string. Therefore, to perform mathematical operations, you must use commands such as let, declare, expr, and parentheses. Shell variables can be divided into local variables and environment variables. Local variables are only available in the shell that creates them. Environment variables can be used in the shell for creating them and any child processes derived from them. Some variables are created by the user, while others are dedicated shell variables. The variable name must start with a letter or underscore. Other characters can be letters or numbers (0 ~ 9) or an underscore. Any other character marks the termination of the variable name. The name is case sensitive. When assigning values to variables, there cannot be any blank characters around the equal sign. To assign a null value to the variable, an equal sign can be followed by a linefeed. You can use the set command to view all variables. The unset var command can clear the variable VAR, which is equivalent to not defined. Readonly VaR can change VaR to a read-only variable and cannot be changed after definition. There are many reference methods for Shell variables. using these methods, you can easily obtain the shell variable value, the length of the variable value, a string of the variable, and the value after the variable is partially replaced. Common shell variables are referenced as follows:

2. Environment Variables
The environment variables are defined as follows:
Var = Value
Export VaR
Shell will execute initialization scripts such as profile during initialization. Some environment variables are defined in the script, which will be passed to the child process when the child process is created.
Use the Env command to view the current environment variables. Common system environment variables are as follows:
_ (Underline) The last parameter of the previous command
Bash expands to the full path name used to call a bash instance.
The search path of the cdpath CD command. It is a list of directories separated by colons, and shell uses it to search for the target directory specified by the CD command. Example .:~ :/Usr
The built-in editor Emacs, gmacs, or VI path name.
Every new bash shell (including scripts) environment file executed by env at startup. The file name assigned to this variable is. bashrc.
EUID expands to the valid ID of the current user initialized at Shell startup.
Group to which the current user belongs
Histfile specifies the file that saves the command line history. The default value is ~ /. Bash_history. If reset, the command line history is not saved when the Interactive Shell exits.
Histsize records the number of commands in the command line history file. The default value is 500.
Home Directory. If no directory is specified, the CD command will switch to this directory
The field delimiter inside ifs, which is generally a space character, Tab character, or line break. It is used to replace the command, and divide the fields of the words generated by the table and read input in the loop structure.
Lang is used to specify the type of the variable that does not start with LC _. locale class
Oldpwd previous working directory
Path command to search for the path. A list of directories separated by colons. Shell uses it to search for commands. A common value is/usr/GNU/bin:/usr/local/bin:/usr/UCB: /usr/bin
Ppid: process ID of the parent process
PS1 main prompt string, default value: $
PS2 prompt string. The default value is>
The selection prompt string used by the PS3 and select commands. The default value is #?
Debug prompt string used when tracing is enabled. The default value is +. Tracing can be enabled with set-X.
The current working directory of PWD. Set by CD
Each time random references this variable, a random integer is generated. Random number sequences can be initialized by assigning values to random. If random is reset, it will lose the specific attribute even if it is set later.
Reply is set when no parameter is provided for read.
When shell is called, It scans the environment variable to find the name. Shell sets the default values for path, PS1, ps2, mailcheck, And ifs. Home and mail are set by login (1 ).
Shellopts contains a column of shell OPTIONS enabled, such as braceexpand, hashall, and monitor.
UID is expanded to the user ID of the current user and initialized at Shell startup.
3. Numeric variable
Shell treats the variable value as a string by default, for example:
Age = 22
Age =$ {age} + 1
Echo $ {age}
The output result is 22 + 1, not 23, because shell interprets it as a string rather than a mathematical operation.
You can use the let command to perform mathematical operations, for example:
Let age =$ {age} + 1
You can also use declare to define the variable as an integer. For example:
Declare-I age = 22
Here we use the-I option to define age as an integer. After each operation, the right value of age is recognized as an arithmetic expression or number.
4 Array
An array can be used in shell, for example:
Array [0] = 0
Array [1] = 1
Array [2] = 2
Array is an array. You can initialize the array as follows:
Array = (0 1 2) // elements are separated by Spaces
You can use $ {array [$ I]} to access an element in array. The returned value of $ {array [*]} is a string composed of all elements of the array, the return value of $ {# array [*]} is the number of elements in the array. $ {array [*]: 0: 2} returns a string composed of the first and second elements. 0 indicates the start position, 2 indicates the number of elements to be returned, and the start position can be 0-2 (0 minus 2), indicating that the last element starts.
Below is an example of a slightly complex point:

1 #!/bin/bash2 for ((i=0; i<100; i++))3 do4 array[$i]=$i5 done6 for ((i=0; i<100; i++))7 do8 echo ${array[$i]}9 done

If you want to use a two-dimensional array or even a three-dimensional array, you need to use the eval command to simulate the Array Function.
The eval command is used to scan the command twice and then execute it. If you do not use Eval, scan it only once and then execute it. Let's look at an example:
[Email protected]: ~ $ Name = Barry
[Email protected]: ~ $ Name = Hello
Barry = Hello: Command not found
Why does an error occur when I assign values to the Barry variable in the second sentence? From the error message, we can find that shell does not recognize this as a value assignment statement, but runs Barry = hello as a command. Of course, an error is reported. Why can't we identify this as a value assignment statement? During the first scan, because the $ symbol is scanned, this sentence cannot be used as a value assignment statement. The left side of the value assignment statement is always a variable name, instead of starting with $. Therefore, the first scan only recognized the $ name variable and replaced it without recognizing the value assignment statement.
What if eval $ name = Hello?
[Email protected]: ~ $ Name = Barry
[Email protected]: ~ $ Name = Hello
Barry = Hello: Command not found
[Email protected]: ~ $ Eval $ name = Hello
[Email protected]: ~ $ Echo $ Barry
Hello
It can be seen that after Eval is used, $ name is replaced for the first scan of $ name = Hello, and no value assignment statement is identified. The second scan is a value assignment statement and then executed. Now we can think about how to use eval to implement a two-dimensional array.
Each row of the following two-dimensional array represents a person's information record, including name and age.

 1 for ((i=0; i<2; i++)) 2 do 3 for ((j=0; j<2; j++)) 4 do  5 read man$i$j 6 done 7 done 8 echo "next print:" 9 for ((i=0; i<2; i++))10 do11 for ((j=0; j<2; j++))12 do 13 eval echo -n "\$man$i$j:"14 done15 printf "\n"16 done

5 Special Variables
$0: File Name of the current script
$ Num: num is a number starting from 1. $1 is the first parameter, $2 is the second parameter, and $ {10} is the tenth parameter.
$ #: Number of input Script Parameters
$ *: All location parameters (as a single string)
[Email protected]: All location parameters (each as an independent string ).
$? : The return value of the previous command in the current shell process. If the previous command is successfully executed, $? The value is 0. Otherwise, it is a non-zero value and is often used as an if statement condition.
$: PID of the Current Shell Process
$! : PID of the last process running in the background
$-: Displays the current options used by shell.
$ _: The last parameter of the previous command.

From http://www.cnblogs.com/barrychiao/archive/2012/10/22/2733210.html

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.