Shell Special variables: Shell $, $#, $*, $@, $, $$, and command-line arguments

Source: Internet
Author: User



Variable names can only contain numbers, letters, and underscores, because some variables that contain other characters have special meanings, and such variables are called special variables.

For example, $ represents the ID of the current shell process, the PID, as shown in the following code:


    1. $echo $$


Run results


29949




List of special variables
variables meaning
$ File name of the current script
$n Arguments passed to the script or function. N is a number that represents the first few parameters. For example, the first parameter is $ $, and the second argument is $ A.
$# The number of arguments passed to the script or function.
$* All parameters passed to the script or function.
[Email protected] All parameters passed to the script or function. When enclosed by double quotation marks (""), it is slightly different from $*, as will be mentioned below.
$? The exit state of the last command, or the return value of the function.
$$ The current shell process ID. For Shell scripts, this is the process ID where the scripts are located.
Command-line arguments


The arguments passed to the script when the script is run are called command-line arguments. Command-line arguments are represented by a $n, for example, $ = for the first argument, and $ for the second argument, and so on.

Take a look at the following script:


    1. #!/bin/bash
    2. echo "File Name: $"
    3. Echo "First Parameter: $ $"
    4. Echo "First Parameter: $"
    5. echo "Quoted Values: [email protected]"
    6. echo "Quoted Values: $*"
    7. echo "Total number of Parameters: $#"


Operation Result:


$./test.sh Zara Ali
File Name : ./test.sh
First Parameter : Zara
Second Parameter : Ali
Quoted Values: Zara Ali
Quoted Values: Zara Ali
Total Number of Parameters : 2
The difference between $* and [email protected]


$* and [email protected] All represent all parameters passed to a function or script, and are not enclosed by double quotation marks (""), with "$" and "$" ... All parameters are output in the form "$n".

But when they are enclosed in double quotation marks (""), "$*" takes all the parameters as a whole and outputs all parameters in the form of "$ $ ... $n"; "[email protected]" separates the various parameters to "$" "$" ... All parameters are output in the form "$n".

The following example can clearly see the difference between $* and [email protected]:


  1. #!/bin/bash
  2. echo "\$*=" $*
  3. echo "\" \$*\ "=" "$* "
  4. echo "\$@=" [email protected]
  5. echo "\" \$@\ "=" [email protected] "
  6. echo "Print each param from \$*"
  7. For Var in $*
  8. Do
  9. echo "$var"
  10. Done
  11. echo "Print each param from \$@"
  12. For Var in [email protected]
  13. Do
  14. echo "$var"
  15. Done
  16. echo "Print each param from \" \$*\ ""
  17. For Var in "$*"
  18. Do
  19. echo "$var"
  20. Done
  21. echo "Print each param from \" \$@\ ""
  22. For Var in "[email protected]"
  23. Do
  24. echo "$var"
  25. Done


Execute./test.sh "a" "B" "C" "D" and see the following result:


$*=  a b c d
"$*"= a b c d
[email protected]=  a b c d
"[email protected]"= a b c d
print each param from $*
a
b
c
d
print each param from [email protected]
a
b
c
d
print each param from "$*"
a b c d
print each param from "[email protected]"
a
b
c
d
Exit status


$? You can get the exit status of the previous command. The so-called exit status is the return result after the last command was executed.

Exit status is a number, in general, most of the command execution succeeds returns 0, and the failure returns 1.

However, there are some commands that return other values that represent different types of errors.

In the following example, the command executes successfully:


$./test.sh Zara Ali
File Name : ./test.sh
First Parameter : Zara
Second Parameter : Ali
Quoted Values: Zara Ali
Quoted Values: Zara Ali
Total Number of Parameters : 2
$echo $?
0
$



$? You can also represent the return value of a function


















1 Shell Variable Basics
The shell variable is a very "weak" variable, by default a variable holds a string, and the shell does not care what the string means. So for mathematical operations, you must use some commands such as let, declare, expr, double brackets, and so on. Shell variables can be divided into two categories: local variables and environment variables. Local variables are only available in the shell in which they are created. Environment variables can be used in the shell in which they are created and in any child processes it derives from. Some variables are created by the user, while others are private shell variables. The variable name must begin with a letter or underscore character. The remaining characters can be letters, numbers (0~9), or underscore characters. Any other character marks the end of the variable name. The name is case sensitive. When assigning a value to a variable, you cannot have any whitespace around the equals sign. To assign a null value to a variable, you can follow a newline character after the equals sign. With the SET command you can see all the variables, the unset var command clears the variable Var,var equivalent to not defined. readonly var can change Var to a read-only variable, and you cannot make any changes to Var after the definition. There are many references to shell variables, which can easily be used to get the value of the shell variable, the length of the variable value, a string of variables, the value of the variable being partially replaced, and so on. Common references to shell variables are as follows:











2 Environment Variables
The environment variables are defined in the following ways:
Var=value
Export Var
During initialization, the shell executes initialization scripts such as profile, which defines environment variables that are passed to the child process when the child process is created.
Use the ENV command to view the current environment variables. The common system environment variables are as follows:
_ (underline) The last parameter of the previous command
Bash expands to the full pathname used when calling bash instances
Cdpath the search path for the CD command. It is a colon-delimited list of directories that the shell uses to search for the target directory specified by the CD command. For example.: ~:/USR
Editor's path name for the built-in editors Emacs, Gmacs, or VI
ENV Every new bash shell (including scripts) that executes when the environment file is launched. The file name that is usually assigned to this variable is. BASHRC.
Euid expands to a valid ID for the current user that was initialized at shell startup
GROUPS the group to which the current user belongs
HISTFILE Specifies the file that holds the command-line history. The default value is ~/.bash_history. If reset, the command line history will not be saved when the interactive shell exits
Histsize the number of commands recorded in the command-line history file. Default is 500
Home Home directory. When a directory is not specified, the CD command will turn to that directory
IFS internal field separators, typically space characters, tab characters, and line breaks, are used to divide the fields of words generated by the command substitution, the table in the looping structure, and the read input
LANG is used to determine the locale class for a type that is not explicitly selected with a variable starting with LC_
Oldpwd Previous working directory
Path command to search for paths. A list of directories separated by colons, which the shell uses to search for commands, a common value of/usr/gnu/bin:/usr/local/bin:/usr/ucb:/usr/bin
PPID Process ID of the parent process
PS1 main prompt string, default value is $
PS2 prompt string, default value is >
PS3 the Select Prompt string to use with the Select command, the default value is #?
PS4 the default value is + when tracing is turned on using the debug prompt string. Tracking can be opened with set–x
PWD Current working directory. Set by CD
Each time the random reference to the variable, a random integer is generated. The sequence of random numbers can be initialized by assigning a value to random. If the random is reset, it will lose a specific attribute even if it is subsequently set
REPLY set when no parameter is given to read
Shell when invoking the shell, it scans the environment variable to find the name. The shell sets default values for path, PS1, PS2, MailCheck, and IFS. Home and mail are set by login (1)
Shellopts contains a list of open shell options, such as Braceexpand, Hashall, monitor, etc.
The UID expands to the user ID of the current user and is initialized at shell startup.
3 Numeric variables
The variable values are treated as strings by default in the shell, for example:
Age=22
Age=${age}+1
Echo ${age}
The output is 22+1, not 23, because the shell interprets it as a string, not a mathematical operation.
You can use the Let command to perform mathematical operations, such as:
Let Age=${age}+1
You can also use declare to define a variable as an integral type. For example:
Declare-i age=22
The-i option is used here to define age as an integer. After each operation, the right value of age is recognized as an arithmetic expression or a number.
4 Arrays
Arrays can be used in the shell, for example:
Array[0]=0
Array[1]=1
array[2]=2
Then array is an array, or it can be initialized to the array:
array= (0 1 2)//elements are separated by a space
You can access an element in an array by ${array[$i]}, the return value of ${array[*]} is a string of all elements of the array, ${the return value of the #array [*]} is the number of elements of the array, ${array[*]:0:2} Returns a string consisting of the first and second elements. 0 indicates the starting position, 2 indicates the number of elements to return, the start position can be 0-2 (0 minus 2), and so on, starting from the penultimate element.
Here is a slightly more complicated example:

 
 
1 #!/bin/bash
2 for ((i=0; i<100; i++))
3 do
4 array[$i]=$i
5 done
6 for ((i=0; i<100; i++))
7 do
8 echo ${array[$i]}
9 done

If you want to use a two-dimensional array or even a three-dimensional array, then you need to use the Eval command to simulate the function of the array.
The function of the eval command is to scan the command two times and then perform the scan only once, if not using eval. Look at an example:
[Email protected]:~$ Name=barry
[Email protected]:~$ $name =hello
Barry=hello:command not found
Why does the second sentence make a mistake in assigning a value to the Barry variable? From the error message can be found that the shell does not recognize that this is an assignment statement, but the Barry=hello as a command to execute, of course, will error. Why can't we recognize that this is an assignment statement? The first scan, because the scan to the $ symbol, so you can not think of this sentence as an assignment statement, the left of the assignment statement is always a variable name, and should not be the beginning of the value. So the first scan only identified the $name variable and replaced it, without recognizing the assignment statement.
What if I use 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
Visible after using eval, the first scan of the $name =hello replaced the $name, no recognition assignment statement, second scan recognition is an assignment statement, and then execute. Now we can think about how to implement a two-dimensional array with eval.
The two-dimensional array implemented below represents a person's information record for each row, including name, 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 do
11 for ((j=0; j<2; j++))
12 do 
13 eval echo -n "\$man$i$j:"
14 done
15 printf "\n"
16 done


5 Special variables
$ A: The file name of the current script
$num: Num is a number starting from 1, and $ is the first argument, and $ is the second argument, ${10} is the tenth argument
$#: Number of arguments passed in the script
$*: All positional parameters (as a single string)
[Email protected]: all positional parameters (each as a separate string).
$?: The return value of the previous command in the current shell process, if the previous command succeeds, the value of $ is 0, otherwise a value other than 0 is commonly used to make an if statement condition
$$: pid of the current shell process
$!: PID of the last process running in the background
$-: Shows the current options used by the shell
$_: Last parameter of previous command



Shell Special variables: Shell $, $#, $*, [email protected], $?, $$ and command line arguments


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.