Variables in Bash script tutorial

Variables in Bash script tutorial

table of Contents

Introduction

Create variable

Read variable

Delete variable

Output variables, export command

Special variable

The default value of the variable

declare command

readonly command

let command


Bash variables are divided into environment variables and custom variables.

Introduction

Environment variables are the variables that come with the Bash environment. They have been defined when entering the Shell and can be used directly. They are usually defined by the system, and they can also be passed in from the parent shell to the child shell by the user.

env
Command or
printenv
Command, you can display all environment variables.

$ env # or $ printenv Copy code

Below are some common environment variables.

  • BASHPID
    : The process ID of the Bash process.
  • BASHOPTS
    The parameters of the current Shell, you can use
    shopt
    Command modification.
  • DISPLAY
    : The name of the monitor in the graphics environment, usually
    :0
    , Which means the first display of X Server.
  • EDITOR
    : The default text editor.
  • HOME
    : The user's home directory.
  • HOST
    : The name of the current host.
  • IFS
    : The separator between words, the default is a space.
  • LANG
    : Character set and language encoding, such as
    zh_CN.UTF-8
    .
  • PATH
    : A list of directories separated by colons. When the executable program name is entered, this directory list will be searched.
  • PS1
    : Shell prompt.
  • PS2
    : When entering multiple lines of commands, the secondary Shell prompt.
  • PWD
    : The current working directory.
  • RANDOM
    : Return a random number between 0 and 32767.
  • SHELL
    : Shell's name.
  • SHELLOPTS
    : Start the current Shell
    set
    For the parameters of the command, refer to the chapter "set command".
  • TERM
    : Terminal type name, that is, the protocol used by the terminal emulator.
  • UID
    : The ID number of the current user.
  • USER
    : The user name of the current user.

Many environment variables rarely change, and they are read-only and can be regarded as constants. Because their variable names are all uppercase, traditionally, if users want to define a constant by themselves, they will also use all uppercase variable names.

Note that Bash variable names are case sensitive,

HOME
with
home
Are two different variables.

To view the value of a single environment variable, you can use

printenv
Command or
echo
command.

The printenv the PATH $ # or $ echo $ the PATH copy the code

note,

printenv
The variable name after the command does not need to be prefixed
$
.

Custom variables are variables defined by the user in the current Shell. They must be defined first and then used, and are only available in the current Shell. Once the current Shell is exited, the variable does not exist.

set
The command can display all variables (including environment variables and custom variables), as well as all Bash functions.

$ setCopy code

 

Create variable

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

  • It consists of letters, numbers and underscore characters.
  • The first character must be a letter or an underscore, not a number.
  • Spaces and punctuation marks are not allowed.

The syntax of variable declaration is as follows.

variable=valueCopy code

In the above command, the left side of the equal sign is the variable name, and the right side is the variable. Note that there can be no spaces on either side of the equal sign.

If the value of the variable contains spaces, you must enclose the value in quotation marks.

= myVar "Hello World" copy the code

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

Below are some examples of custom variables.

a=z # The variable a is assigned to the string z b= "a string" # The variable value contains spaces, so it must be placed in quotation marks c= "a string and $b " # The variable value can refer to the value of other variables d= "/t\ta string\n" # Variable value can use escape character e=$(ls -l foo.txt) # Variable value can be the result of command execution f=$(( 5 * 7 )) # Variable value can is the result of mathematical operations copy the code

Variables can be assigned repeatedly, and subsequent assignments will overwrite previous assignments.

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

In the above example, the variable

foo
The second assignment will overwrite the first assignment.

 

Read variable

When reading variables, add directly before the variable name

$
That's it.

$ foo=bar $ echo $foo bar Copy code

Whenever Shell sees

$
At the beginning of the word, it will try to read the value corresponding to the variable name.

If the variable does not exist, Bash will not report an error, but will output a null character.

due to

$
It has a special meaning in Bash. When using it as a dollar sign, you must be very careful.

$ echo The total is $100 .00 The total is 00.00 Copy code

The original intent of the above command is to enter

$100
, But Bash will
$1
Interpreted as a variable, the variable is empty, so the input becomes
00.00
. So if you want to use
$
The original meaning of need to be in
$
Put a backslash in front to escape it.

$ echo The total is/$100 .00 The total is $100 .00Copy code

When reading variables, variable names can also use curly braces

{}
Surrounded, such as
$a
Can also be written as
${a}
. This type of writing can be used when the variable name is used in conjunction with other characters.

$ a=foo $ echo $a_file $ echo ${a} _file foo_file Copy code

In the above code, the variable name

a_file
There will be no output, because Bash interprets it as a variable, and this variable does not exist. Only distinguished by curly braces
$a
, Bash can interpret it correctly.

In fact, the syntax for reading variables

$foo
, Can be seen as
${foo}
Short form of.

If the value of the variable itself is also a variable, you can use

${!varname}
The syntax to read the final value.

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

In the above example, the variable

myvar
The value is
USER
,
${!myvar}
The writing method expands it into the final value.

 

Delete variable

unset
The command is used to delete a variable.

unset NAMECopy code

This command is not very useful. Because the non-existent Bash variable is always equal to the empty string, so even

unset
If the command deletes the variable, the variable can still be read, and the value is an empty string.

Therefore, to delete a variable, you can also set this variable to an empty string.

$ foo = '' $ foo= Copy code

In the above two ways of writing, the variables are deleted

foo
. Since the non-existent value defaults to an empty string, the latter method can write no value on the right side of the equal sign.

 

Output variables, export command

The variables created by the user can only be used in the current shell, and the child shell cannot read the variables defined by the parent shell by default. In order to pass variables to the child Shell, you need to use

export
command. The variables output in this way are environment variables for the child shell.

export
Commands are used to output variables to the sub-Shell.

NAME=foo export NAMEcopy code

The above command outputs the variable

NAME
. Variable assignment and output can also be done in one step.

export NAME=valueCopy code

After the above command is executed, the current Shell and the newly created sub-Shell can read variables

$NAME
.

If the child shell modifies the inherited variables, the parent shell will not be affected.

# Output variable $foo $ export foo=bar # New Sub Shell $ bash # Read $foo $ echo $foo bar # Modify inherited variables $ foo=baz # Exit the child Shell $ exit # Read $foo $ echo $foo bar Copy code

In the above example, the child Shell has modified the inherited variables

$foo
, Has no effect on the parent Shell.

 

Special variable

Bash provides some special variables. The values of these variables are provided by Shell, and users cannot assign values.

(1)

$?

$?
It is the exit code of the previous command, used to determine whether the previous command was executed successfully. The return value is
0
, Indicates that the previous command was executed successfully; if it is non-zero, the previous command failed to execute.

$ ls doesnotexist ls: doesnotexist: No such file or directory $ echo $? 1 Copy code

In the above example,

ls
Command to view a file that does not exist, resulting in an error.
$?
It is 1, indicating that the execution of the previous command failed.

(2)

$$

$$
Is the process ID of the current Shell.

$ echo $$ 10662 Copy code

This special variable can be used to name temporary files.

LOGFILE=/tmp/output_log.$$ Copy code

(3)

$_

$_
It is the last parameter of the previous command.

$ grep dictionary/usr/share/dict/words dictionary $ echo $_ /usr/share/dict/words Copy code

(4)

$!

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

$ firefox & [1] 11064 $ echo $! 11064 Copy code

In the above example,

firefox
Is a command that runs in the background,
$!
Returns the process ID of the command.

(5)

$0

$0
It is the name of the current Shell (when executed directly on the command line) or the name of the script (when executed in a script).

$ echo $0 bash Copy code

In the above example,

$0
It returns that Bash is currently running.

(6)

$-

$-
It is the startup parameter of the current Shell.

$ echo $- himBHs Copy code

(7)

$@
with
$#

$@
with
$#
Indicates the number of parameters of the script, see chapter Script.

 

The default value of the variable

Bash provides four special syntaxes, which are related to the default value of the variable, the purpose is to ensure that the variable is not empty.

${varname:-word} Copy code

The meaning of the above syntax is that if the variable

varname
Exists and is not empty, then return its value, otherwise return
word
. Its purpose is to return a default value, such as
${count:-0}
Representation variable
count
Return if it doesn't exist
0
.

${varname:=word} Copy code

The meaning of the above syntax is that if the variable

varname
Exists and is not empty, then return its value, otherwise set it to
word
And return
word
. Its purpose is to set the default value of the variable, such as
${count:=0}
Representation variable
count
Return if it doesn't exist
0
, And will
count
Set to
0
.

${varname:+word} Copy code

The meaning of the above syntax is, if the variable name exists and is not empty, it will return

word
, Otherwise it returns a null value. Its purpose is to test whether the variable exists, such as
${count:+1}
Representation variable
count
Return if it exists
1
(Represents
true
), otherwise it returns a null value.

${varname:?message} Copy code

The meaning of the above syntax is that if the variable

varname
Exist and not empty, then return its value, otherwise print out
varname: message
, And interrupt the execution of the script. If omitted
message
, The default information "parameter null or not set." is output. Its purpose is to prevent variables from being undefined, such as
${count:?"undefined!"}
Representation variable
count
When it is not defined, the execution is interrupted, an error is thrown, and the given error message is returned
undefined!
.

If the above four syntaxes are used in a script, numbers can be used in the variable name

1
To
9
, Which represents the parameters of the script.

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

The above code appears in the script,

1
Represents the first parameter of the script. If the parameter does not exist, exit the script and report an error.

 

declare command

declare
Commands can declare some special types of variables and set some restrictions for variables, such as declaring read-only variables and integer variables.

Its grammatical form is as follows.

DECLARE the OPTION value = the VARIABLE duplicated code

declare
The main parameters (OPTION) of the command are as follows.

  • -a
    : Declare array variables.
  • -f
    : Output all function definitions.
  • -F
    : Output all function names.
  • -i
    : Declare integer variables.
  • -l
    : Declare variables as lowercase letters.
  • -p
    : View variable information.
  • -r
    : Declare read-only variables.
  • -u
    : Declare variables in uppercase letters.
  • -x
    : The variable is output as an environment variable.

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

Without any parameters,

declare
The command outputs all variables of the current environment, including functions, which are equivalent to those without any parameters
set
command.

$ DECLARE copy the code

(1)

-i
parameter

-i
After the parameter declares the integer variable, you can directly perform mathematical operations.

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

In the above example, if the variable

result
Is not declared as an integer,
val1*val2
Will be treated as a literal and will not perform integer arithmetic. In addition,
val1
with
val2
In fact, it does not need to be declared as an integer, because as long as
result
Declared as an integer, its assignment will be automatically interpreted as an integer operation.

Note that after a variable is declared as an integer, it can still be rewritten as a string.

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

In the above example, the variable

var
Declared as an integer. After overwriting, Bash will not report an error, but will assign an indeterminate value. In the above example, it may output 0, or it may output 3.

(2)

-x
parameter

-x
The parameters are equivalent to
export
Command, you can output an environment variable whose variable is a sub-Shell.

$ DECLARE -x foo # is equivalent to $ Export foo copy the code

(3)

-r
parameter

-r
Parameters can declare read-only variables, cannot change the value of the variable, and cannot
unset
variable.

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

In the above example, the last two assignment statements will report an error and the command execution fails.

(4)

-u
parameter

-u
The parameter declaration variable is in uppercase letters, and the variable value can be automatically converted to uppercase letters.

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

(5)

-l
parameter

-l
The parameter declaration variable is in lowercase letters, and the variable value can be automatically converted to lowercase letters.

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

(6)

-p
parameter

-p
Parameters output variable information.

$ foo=hello $ declare -p foo declare - foo = "hello" $ declare -p bar bar: not found Copy code

In the above example,

declare -p
The value of the defined variable can be output, and for the undefined variable, it will prompt that it cannot be found.

If the variable name is not provided,

declare -p
Output information about all variables.

$ DECLARE -p Copy the code
$ Declare -p Copy the code

(7)

-f
parameter

-f
Parameters output all functions of the current environment, including its definition.

$ DECLARE -f Copy the code

(8)

-F
parameter

-F
The parameter outputs the names of all functions in the current environment, excluding function definitions.

$ DECLARE -F copy the code

 

readonly command

readonly
The command is equivalent to
declare -r
, Used to declare read-only variables, can not change the value of the variable, nor
unset
variable.

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

In the above example, change the read-only variable

foo
An error will be reported and the command execution will fail.

readonly
The command has three parameters.

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

 

let command

let
When the command declares a variable, you can directly execute arithmetic expressions.

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

In the above example,

let
The command can be calculated directly
1 + 2
.

let
If the parameter expression of the command contains spaces, quotation marks are required.

$ The let "foo =. 1 + 2" copy the code

let
Multiple variables can be assigned at the same time, and the assignment expressions are separated by spaces.

$ let "v1 = 1" "v2 = v1++" $ echo $v1 , $v2 2,1 Copy code

In the above example,

let
Two variables are declared
v1
with
v2
,among them
v2
equal
v1++
To return first
v1
Value, then
v1
Self-increasing.

 

 

String manipulation in the next section of Bash script tutorial