directory

Introduction to the

Create a variable

Read the variable

To delete a variable

Output the variable, export command

Special variables

The default value of a variable

Declare the command

Readonly command

The let command


Bash variables are divided into environment variables and custom variables.

Introduction to the

Environment variables are native to the Bash environment and are defined when you enter the Shell and can be used directly. They are usually system-defined and can also be passed by the user from the parent Shell to the child Shell.

The env command or printenv command can display all environment variables.

$ env
# or
$ printenv
Copy the code

Here are some common environment variables.

  • BASHPID: Specifies the Bash process ID.
  • BASHOPTS: Is an argument to the current ShellshoptCommand modify.
  • DISPLAY: The display name of the graphics environment, usually: 0Represents the first display of the X Server.
  • EDITOR: The default text editor.
  • HOME: Indicates the user’s home directory.
  • HOST: Indicates the name of the current host.
  • IFS: Delimiter between words. Default is space.
  • LANG: character set and language encoding, for examplezh_CN.UTF-8.
  • PATH: A list of directories separated by colons that will be searched when an executable name is entered.
  • PS1: Shell prompt.
  • PS2: Secondary Shell prompt for typing multi-line commands.
  • PWD: Current working directory.
  • RANDOM: Returns a random number between 0 and 32767.
  • SHELL: The name of the Shell.
  • SHELLOPTS: starts the current ShellsetFor details about command parameters, see set Command.
  • TERM: The name of the terminal type, which is the protocol used by the terminal emulator.
  • UID: INDICATES the ID of the current user.
  • USER: Indicates the name of the current user.

Many environment variables rarely change, are read-only and can be treated as constants. Because their variable names are all uppercase, traditionally, if the user wanted to define a constant himself, the variable name would also be all uppercase.

Note that Bash variable names are case sensitive, and HOME and HOME are two different variables.

To view the value of a single environment variable, use the printenv command or the echo command.

$ printenv PATH
# or
$ echo $PATH
Copy the code

Note that the variable name after the printenv command is not prefixed with $.

Custom variables are variables defined by the user in the current Shell. They must be defined before being used and are available only in the current Shell. Once you exit the current Shell, the variable is gone.

The set command displays all variables (both environment and custom), as well as all Bash functions.

$ set
Copy the code

 

Create a variable

When a user creates a variable, the variable name must comply with the following rules.

  • The value contains letters, digits, and underscores (_).
  • The first character must be a letter or an underscore, not a number.
  • Spaces and punctuation are not allowed.

The syntax for variable declarations is as follows.

variable=value
Copy the code

In the above command, the left side of the equals sign is the variable name, and the right side is the variable. Notice that you can’t have Spaces on either side of the equal sign.

If the value of a variable contains Spaces, you must place the value in quotes.

myvar="hello world"
Copy the code

Bash has no concept of data types, and all variable values are strings.

Here are some examples of custom variables.

a=z                     The variable a is assigned to the string z
b="a string"            # Variable values that contain Spaces must be enclosed in quotes
c="a string and $b"     The value of a variable can refer to the value of another variable
d="\t\ta string\n"      # Variable values can use escape characters
e=$(ls -l foo.txt)      The value of a variable can be the result of a command execution
f=$((5 * 7))            # Variable values can be the result of mathematical operations
Copy the code

Variables can be assigned repeatedly, with subsequent assignments overwriting previous assignments.

$ foo=1
$ foo=2
$ echo $foo
2
Copy the code

In the example above, the second assignment to the variable foo overrides the first assignment.

 

Read the variable

When reading a variable, simply prefix the variable name with $.

$ foo=bar
$ echo $foo
bar
Copy the code

Every time the Shell sees a word beginning with $, it tries to read the value of the variable name.

If the variable does not exist, Bash does not report an error, but prints null characters.

Because $has a special meaning in Bash, you must be careful when using it as a dollar sign,

$ echo The total is The $10000 The total is 00.00Copy the code

The original intention of the command was to type $100, but Bash interprets $1 as a variable, which is empty, so the input becomes 00.00. So, if you want to use the $literal, you need to escape it by putting a backslash before it.

$ echo The total is \The $100.00
The total is The $10000.Copy the code

When reading a variable, the variable name can also be surrounded by curly braces {}, for example, $a can also be written as ${a}. This can be used when a variable name is used with other characters.

$ a=foo
$ echo $a_file

$ echo ${a}_file
foo_file
Copy the code

In the above code, the variable name a_file won’t output anything because Bash interprets it as a variable in its entirety, and that variable doesn’t exist. Bash can only be read correctly if $a is distinguished by curly braces.

In fact, the syntax for reading variables, $foo, can be thought of as a shorthand for ${foo}.

If the value of a variable is itself a variable, use ${! Varname} syntax, read the final value.

$ myvar=USER
$ echo The ${! myvar}
ruanyf
Copy the code

In the example above, the value of myvar is USER, ${! Myvar} is written to expand it to the final value.

 

To delete a variable

Using the unset command, you can delete a variable.

unset NAME
Copy the code

This command is not very useful. Because nonexistent Bash variables are uniformly equal to an empty string, the variable can be read with an empty string value even if the unset command removes the variable.

So, if you delete a variable, you can also set that variable to an empty string.

$ foo=' '
$ foo=
Copy the code

In both cases, the variable foo is deleted. Since nonexistent values default to an empty string, the latter can be written without any value to the right of the equals sign.

 

Output the variable, export command

Variables created by the user can only be used by the current Shell. Variables defined by the parent Shell cannot be read by the child Shell by default. To pass variables to subshells, use the export command. The output variables are environment variables for the child Shell.

Using the export command, you can output variables to the subshell.

NAME=foo
export NAME
Copy the code

The above command outputs the variable NAME. Variable assignment and output can also be done in one step.

export NAME=value
Copy the code

After executing the command above, the current Shell and any subsequentially created child Shell can read the variable $NAME.

If the child Shell changes an inherited variable, it does not affect the parent Shell.

# output variable $foo
$ export foo=bar

Create a new subshell
$ bash

# read $foo
$ echo $foo
bar

# modify inherited variables
$ foo=baz

Exit the subshell
$ exit

# read $foo
$ echo $foo
bar
Copy the code

In the example above, the child Shell modifies the inherited variable $foo without affecting the parent Shell.

 

Special variables

Bash provides some special variables. The values of these variables are provided by the Shell and cannot be assigned by the user.

(1) $?

$? Is the exit code of the previous command, which is used to determine whether the previous command is successfully executed. If the return value is 0, the previous command is successfully executed. If it is non-zero, the previous command fails to be executed.

$ ls doesnotexist
ls: doesnotexist: No such file or directory

$ echo $?
1
Copy the code

In the example above, the ls command looks at a file that does not exist, causing an error. $? If the value is 1, the previous command failed to be executed.

(2) $$

$$is the process ID of the current Shell.

$ echo$$10662Copy the code

This special variable can be used to name temporary files.

LOGFILE=/tmp/output_log.$$
Copy the code

(3) the $_

$_ is the last parameter of the previous command.

$ grep dictionary /usr/share/dict/words
dictionary

$ echo The $_
/usr/share/dict/words
Copy the code

(4) $!

$! Is the process ID of the last asynchronous command executed in the background.

$ firefox &
[1] 11064

$ echo $!
11064
Copy the code

In the example above, Firefox is the command running in the background, $! Returns the process ID of the command.

(5) $0

$0 is the name of the current Shell (when executed directly from the command line) or the name of the script (when executed within the script).

$ echo $0
bash
Copy the code

In the example above, $0 returns that Bash is currently running.

(6) $-

$- is the startup parameter of the current Shell.

$ echo $-
himBHs
Copy the code

$@ and $#

$@ and $# indicate the number of arguments in the script. See the script chapter.

 

The default value of a variable

Bash provides four special syntax, related to the default values of variables, to ensure that variables are not null.

${varname:-word}
Copy the code

The syntax above means that the variable varname is returned if it exists and is not empty, otherwise word is returned. Its purpose is to return a default value, such as ${count:-0} to return 0 if the variable count does not exist.

${varname:=word}
Copy the code

The syntax above means that the variable varname is returned if it exists and is not empty, otherwise it is set to Word, and word is returned. Its purpose is to set the default value of the variable, such as ${count:=0} to return 0 if the variable count does not exist, and set count to 0.

${varname:+word}
Copy the code

The syntax above means that word is returned if the variable name exists and is not empty, otherwise null is returned. Its purpose is to test for the presence of a variable, such as ${count:+1}, which returns 1 (true) if the variable count exists, or null otherwise.

${varname:? message}
Copy the code

The implication of the above syntax is that the variable varname is returned if it exists and is not empty, otherwise varname: message is printed and execution of the script is interrupted. If message is omitted, the default message “parameter null or not set.” is printed. Its purpose is to prevent variables from being undefined, such as ${count:? undefined!” } if count is undefined, abort execution, throw an error, return the given error message undefined! .

If the above syntax is used in a script, the variable name part can use the numbers 1 through 9 to indicate the script parameters.

filename=The ${1:?" filename missing."}
Copy the code

The above code appears in the script, where 1 represents the first argument to the script. If it does not exist, exit the script with an error.

 

Declare the command

The declare command can declare variables of special types and set restrictions on variables, such as declaring read-only and integer variables.

Its syntax is as follows.

declare OPTION VARIABLE=value
Copy the code

The main parameter (OPTION) of the declare command is as follows.

  • -a: Declares array variables.
  • -f: Outputs all function definitions.
  • -F: Displays all function names.
  • -i: Declares integer variables.
  • -l: Declares variables to be lowercase letters.
  • -p: Displays variable information.
  • -r: Declares read-only variables.
  • -u: Declares variables in uppercase letters.
  • -x: This variable is output as an environment variable.

If the declare command is used in a function, the declared variables are valid only inside the function, which is equivalent to the local command.

With no arguments, the declare command outputs all variables of the current environment, including functions, equivalent to the set command with no arguments.

$ declare
Copy the code

(1)-iparameter

After the -i parameter is declared as an integer variable, the math operation can be performed directly.

$ declare -i val1=12 val2=5
$ declare -i result
$ result=val1*val2
$ echo $result
60
Copy the code

In the example above, if the variable result is not declared as an integer, val1*val2 is treated as a literal and will not be evaluated as an integer. Also, val1 and val2 do not need to be declared as integers, because as long as result is declared as an integer, its assignment is automatically interpreted as an integer operation.

Note that a variable declared as an integer can still be overwritten as a string.

$ declare -i var=12
$ var=foo
$ echo $var
0
Copy the code

In the above example, the variable var is declared as an integer. After overwriting, Bash does not report an error, but it assigns an indeterminate value, which may be 0 or 3 in the above example.

(2)-xparameter

The -x argument is equivalent to the export command, which outputs an environment variable as a subshell.

$ declare -x foo
# is equal to
$ export foo
Copy the code

(3)-rparameter

The -r argument can declare read-only variables, cannot change their value, and cannot unset variables.

$ declare-r bar=1 $bar=2 bash: bar: read-only variable $echo $?
1

$ unsetBar bash: bar: read-only variable $echo $?
1
Copy the code

In the example above, the last two assignment statements both fail and the command fails to execute.

(4)-uparameter

The -u parameter declares variables to be uppercase letters and automatically converts the value of variables to uppercase letters.

$ declare -u foo
$ foo=upper
$ echo $foo
UPPER
Copy the code

(5)-lparameter

The -l parameter declares variables to be lowercase letters, which can automatically convert variable values to lowercase letters.

$ declare -l bar
$ bar=LOWER
$ echo $bar
lower
Copy the code

(6)-pparameter

-p Displays variable information.

$ foo=hello
$ declare -p foo
declare -- foo="hello"
$ declare-p bar bar: Not foundCopy the code

In the above example, declare -p can print the value of a defined variable, but for undefined variables, a message is displayed indicating that it could not be found.

If no variable name is provided, declare -p prints information about all variables.

$ declare -p
Copy the code
$ declare -p
Copy the code

(7)-fparameter

The -f argument outputs all the functions of the current environment, including its definition.

$ declare -f
Copy the code

(8)-Fparameter

The -f argument displays all function names in the current environment, excluding function definitions.

$ declare -F
Copy the code

 

Readonly command

The readonly command is equivalent to declare -r. It is used to declare read-only variables and cannot change variable values or unset variables.

$ readonlyFoo =1 $foo=2 bash: foo: read-only variable $echo $?
1
Copy the code

In the example above, changing the read-only variable foo causes an error and command execution fails.

The readonly command takes three parameters.

  • -f: The declared variable is the function name.
  • -p: Prints out all read-only variables.
  • -a: Declares an array of variables.

 

The let command

When you declare variables with the let command, you can execute arithmetic expressions directly.

$ let foo=1+2
$ echo $foo
3
Copy the code

In the example above, the let command evaluates 1 + 2 directly.

If the parameter expression of the let command contains Spaces, you need to use quotation marks.

$ let "foo = 1 + 2"
Copy the code

Let can assign to multiple variables at the same time, with assignment expressions separated by Spaces.

$ let "v1 = 1" "v2 = v1++"
$ echo $v1.$v22, 1Copy the code

In the above example, let declares two variables v1 and v2, where v2 equals v1++, indicating that the value of v1 is returned first, and then v1 increases.

 

 

The next section of the Bash script tutorial on string manipulation