当前位置:网站首页>The use of variables in shell that you have to be familiar with
The use of variables in shell that you have to be familiar with
2022-06-29 11:08:00 【ghostwritten】
Shell Variable
List of articles
1. brief introduction
Bash Variables are divided into environment variables and user-defined variables .
1.1 environment variable
The environment variable is Bash Variables that come with the environment , Get into Shell It's already defined , You can use it directly . They are usually system defined , It can also be done by the user from the parent Shell Afferent Shell.
env Order or printenv command , You can display all environment variables .
$ env
# perhaps
$ printenv
Here are some common environment variables .
BASHPID:Bash Process of process ID.BASHOPTS: At present Shell Parameters of , It can be used shopt Command to change .DISPLAY: The name of the display in the graphics environment , Usually :0, Express X Server The first display of .EDITOR: The default text editor .HOME: User's home directory .HOST: The name of the current host .IFS: A separator between words , Default is space .LANG: Character sets and language coding , such as zh_CN.UTF-8.PATH: List of directories separated by colons , When you enter the name of the executable program , Will search this directory list .PS1:Shell Prompt .PS2: When entering a multiline command , Secondary Shell Prompt .PWD: Current working directory .RANDOM: Return to one 0 To 32767 Random number between .SHELL:Shell Name .SHELLOPTS: Start the current Shell Of set Arguments to the commandTERM: Terminal type name , That is, the protocol used by the terminal emulator .UID: Current user's ID Number .USER: The user name of the current user .
Many environment variables rarely change , And it's read-only , Can be treated as a constant . Because their variable names are all uppercase , So traditionally , If you want to define a constant by yourself , Variable names in all uppercase are also used .
[!NOTE|style:flat|lable:Mylable|iconVisibility:hidden]
Bash Variable names are case sensitive ,HOME and home It's two different variables .
View the value of a single environment variable , have access to printenv Order or echo command .
$ printenv PATH
# perhaps
$ echo $PATH
[!NOTE|style:flat|lable:Mylable|iconVisibility:hidden]
printenv The variable name after the command , No prefixes $.
1.2 Custom variable
The user-defined variable is the user's current Shell Variables defined by itself , At present only Shell You can use . Once you exit the current Shell, The variable does not exist .
set The command can display all variables ( Including environment variables and custom variables ), And all Bash function .
$ set
2. Create variables
When users create variables , Variable names must follow the following rules .
- Letter 、 Number and underscore characters .
- The first character must be a letter or an underline , It can't be a number .
- Spaces and punctuation are not allowed .
The syntax for variable declaration is as follows .
variable=value
In the above command , To the left of the equal sign is the variable name , On the right is the variable . Be careful , There can be no spaces on either side of the equal sign .
If the value of the variable contains spaces , You must put the value in quotation marks .
myvar="hello world"
Bash There is no concept of data types , All variable values are strings .
Here are some examples of custom variables .
a=z # Variable a Assign as string z
b="a string" # The variable value contains spaces , You have to put it in quotation marks
c="a string and $b" # Variable values can refer to the values of other variables
d="\t\ta string\n" # Variable values can use escape characters
e=$(ls -l foo.txt) # The variable value can be the result of the execution of the command
f=$((5 * 7)) # Variable values can be the result of mathematical operations
Variables can be assigned repeatedly , Subsequent assignments will overwrite the previous assignments .
$ foo=1
$ foo=2
$ echo $foo
2
In the example above , Variable foo The second assignment of will overwrite the first assignment .
If multiple variables are defined on the same line , You must use a semicolon (;) Separate .
$ foo=1;bar=2
In the example above , The same line defines foo and bar Two variables .
3. Read variables
When reading variables , Add... Directly before the variable name $ That's all right. .
$ foo=bar
$ echo $foo
bar
whenever Shell See with $ When the first word , Will try to read the value corresponding to the variable name .
If the variable does not exist ,Bash No mistake. , It will output null characters .
because $ stay Bash Has a special meaning in , When used as a dollar sign , Be very careful ,
$ echo The total is $100.00
The total is 00.00
The original meaning of the above command is to enter $100, however Bash take $1 Interpretation becomes variable , The variable is empty , So the input becomes 00.00. therefore , If you want to use $ Original meaning of , Need to be in $ Put a backslash before it , Transference .
$ echo The total is \$100.00
The total is $100.00
When reading variables , Variable names can also use curly braces {} Surround , such as $a Or you could write it as ${a}. This method can be used when variable names are used with other characters .
$ a=foo
$ echo $a_file
$ echo ${a}_file
foo_file
In the above code , Variable name a_file There won't be any output , because Bash Interpret it as a variable in its entirety , This variable does not exist . Only use curly brackets to distinguish $a,Bash To correctly interpret .
in fact , Syntax for reading variables $foo, It can be seen as ${foo} Short form of .
If the value of the variable is also a variable itself , have access to ${!varname} The grammar of , Read the final value .
$ myvar=USER
$ echo ${
!myvar}
ruanyf
In the example above , Variable myvar The value of is USER,${!myvar} Is expanded to the final value .
If the variable value contains consecutive spaces ( Or tabs and line breaks ), It's best to read in double quotation marks .
$ a="1 2 3"
$ echo $a
1 2 3
$ echo "$a"
1 2 3
In the above example , Variable a The value of contains two consecutive spaces . If read directly ,Shell Will merge consecutive spaces into one . Read only in double quotation marks , To keep the original format .
4. Delete variables
unset The command is used to delete a variable .
unset NAME
This command is not very useful . Because it doesn't exist Bash Variables are always equal to empty strings , So even unset The command deletes the variable , You can still read this variable , The value is an empty string .
therefore , Delete a variable , You can also set this variable to an empty string .
$ foo=''
$ foo=
The above two ways , The variables are deleted foo. Since the nonexistent value defaults to an empty string , So the latter method can write no value to the right of the equal sign .
5. Output variables ,export command
User created variables can only be used for the current Shell, Son Shell By default, the parent cannot be read Shell Variables defined . To pass a variable to a child Shell, Need to use export command . So the output variables , For son Shell Environment variables .
export Commands are used to send messages to children Shell Output variables .
NAME=foo
export NAME
The above command outputs variables NAME. The assignment and output of variables can also be done in one step .
export NAME=value
After the above command is executed , At present Shell And then the new son Shell, Can read variables $NAME.
Son Shell If you modify the inherited variable , It doesn't affect the father Shell.
# Output variables $foo
$ export foo=bar
# New son Shell
$ bash
# Read $foo
$ echo $foo
bar
# Modify inherited variables
$ foo=baz
# Quitters Shell
$ exit
# Read $foo
$ echo $foo
bar
In the example above , Son Shell Modified inherited variables $foo, To the father Shell No impact .
6. Special variables
Bash Provide some special variables . The values of these variables are determined by Shell Provide , The user cannot assign values .
6.1 $?
$? The exit code for the previous command , Used to determine whether the last command was successfully executed . The return value is 0, Indicates that the last command was executed successfully ; If it's not zero , Indicates that the last command failed to execute .
$ ls doesnotexist
ls: doesnotexist: No such file or directory
$ echo $?
1
In the example above ,ls Command to view a file that does not exist , Result in an error .$? by 1, Indicates that the last command failed to execute .
6.2 $$
$$ For the current Shell The process of ID.
$ echo $$
10662
This special variable can be used to name temporary files .
LOGFILE=/tmp/output_log.$$
6.3 $_
$_ For the last parameter of the previous command .
$ grep dictionary /usr/share/dict/words
dictionary
$ echo $_
/usr/share/dict/words
6.4 $!
$! A process for the last asynchronous command executed in the background ID.
$ firefox &
[1] 11064
$ echo $!
11064
In the example above ,firefox It's a command that runs in the background ,$! Returns the process of the command ID.
6.5 $0
$0 For the current Shell The name of ( When executed directly from the command line ) Or script name ( When executing in a script ).
$ echo $0
bash
In the example above ,$0 Return to the currently running Bash.
6.6 $-
$- For the current Shell Start parameter of .
$ echo $-
himBHs
6.7 [email protected] and $#
$# Indicates the number of parameters in the script ,[email protected] Represents the parameter value of the script
7. Default value of variable
Bash Provides four special grammars , It's about the default value of the variable , The purpose is to ensure that the variable is not empty .
${varname:-word}
The meaning of the above grammar is , If the variable varname It exists and is not empty , Then return its value , Otherwise return to word. The goal is to return a default value , such as ${count:-0} Said variable count Return... When not present 0.
${varname:=word}
The meaning of the above grammar is , If the variable varname It exists and is not empty , Then return its value , Otherwise, set it to word, And back to word. It is the default value of the variable , such as ${count:=0} Said variable count Return... When not present 0, And will count Set to 0.
${varname:+word}
The meaning of the above grammar is , If the variable name exists and is not empty , Then return to word, Otherwise, a null value is returned . Its purpose is to test whether variables exist , such as ${count:+1} Said variable count Return when there is 1( Express true), Otherwise, a null value is returned .
${varname:?message}
The meaning of the above grammar is , If the variable varname It exists and is not empty , Then return its value , Or print it out varname: message, And interrupt the execution of the script . If you omit message, The default information is output “parameter null or not set.”. It is designed to prevent variables from being undefined , such as ${count:?"undefined!"} Said variable count Break execution when undefined , Throw an error , Return the given error message undefined!.
If the above four grammars are used in scripts , The part of the variable name can be numbered 1 To 9, Represents the parameters of the script .
filename=${1:?"filename missing."}
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 .
8. declare command
declare Commands can declare variables of special types , Set some restrictions on variables , For example, declare variables of read-only type and variables of integer type .
Its grammatical form is as follows .
declare OPTION VARIABLE=value
declare The main parameters of the command (OPTION) 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 variable .-u: Declare variables in uppercase .-x: The output of this variable is environment variable .
declare If the command is used in a function , Declared variables are only valid inside functions , Equate to local command .
Without any parameters ,declare Command outputs all variables of the current environment , Including functions , Equivalent to... Without any parameters set command .
$ declare
8.1 -i Parameters
-i Parameters declare integer variables after , You can do math directly .
$ declare -i val1=12 val2=5
$ declare -i result
$ result=val1*val2
$ echo $result
60
In the example above , If the variable result Not declared as an integer ,val1*val2 Will be taken as literal , No integer operation . in addition ,val1 and val2 You don't need to declare it as an integer , Because as long as result Declared as an integer , Its assignment is automatically interpreted as an integer operation .
[!NOTE|style:flat|lable:Mylable|iconVisibility:hidden]
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
In the example above , Variable var Declared as an integer , After covering ,Bash No mistake. , But it will be given an uncertain value , In the above example, it is possible to output 0, It may also output 3.
8.2 -x Parameters
-x The parameter is equal to export command , You can output a variable as a child Shell Environment variables of .
$ declare -x foo
# Equate to
$ export foo
8.3 -r Parameters
-r Parameters can declare read-only variables , Cannot change variable value , Also can not unset Variable .
$ declare -r bar=1
$ bar=2
bash: bar: A read-only variable
$ echo $?
1
$ unset bar
bash: bar: A read-only variable
$ echo $?
1
In the example above , The last two assignment statements will report an error , Command execution failed .
8.4 -u Parameters
-u Parameters declare variables in uppercase , You can automatically convert variable values to uppercase letters .
$ declare -u foo
$ foo=upper
$ echo $foo
UPPER
8.5 -l Parameters
-l Parameters declare variables as lowercase letters , You can automatically convert variable values to lowercase letters .
$ declare -l bar
$ bar=LOWER
$ echo $bar
lower
8.6 -p Parameters
-p Parameter output variable information .
$ foo=hello
$ declare -p foo
declare -- foo="hello"
$ declare -p bar
bar: Not found
In the example above ,declare -p You can output the value of a defined variable , For undefined variables , Will prompt that .
If you don't provide a variable name ,declare -p Output the information of all variables .
$ declare -p
8.7 -f Parameters
-f Parameter outputs all functions of the current environment , Including its definition .
$ declare -f
8.8 -F Parameters
-F Parameter outputs all function names of the current environment , Does not contain function definitions .
$ declare -F
9. readonly command
readonly An order is equal to declare -r, Used to declare read-only variables , You can't change the value of a variable , Also can not unset Variable .
$ readonly foo=1
$ foo=2
bash: foo: A read-only variable
$ echo $?
1
In the example above , Change read-only variables foo Will report a mistake , Command execution failed .
readonly The command has three arguments .
-f: The declared variable is the function name .-p: Print out all read-only variables .-a: The declared variables are arrays .
10. let command
let When a variable is declared , You can execute arithmetic expressions directly .
$ let foo=1+2
$ echo $foo
3
In the example above ,let Commands can calculate directly 1 + 2.
let If the parameter expression of the command contains spaces , You need to use quotation marks .
$ let "foo = 1 + 2"
let You can assign values to multiple variables at the same time , Assignment expressions are separated by spaces .
$ let "v1 = 1" "v2 = v1++"
$ echo $v1,$v2
2,1
In the example above ,let Two variables declared v1 and v2, among v2 be equal to v1++, To return first v1 Value , then v1 Self increasing .
Reference resources :
边栏推荐
- 9 款好用到爆的 JSON 处理工具,极大提高效率!
- 嵌入式驱动开发之uboot---uboot 中的常见命令参数参数
- MySQL get table information
- STM32F1与STM32CubeIDE编程实例-超声波测距传感器驱动
- Xiaomi mobile phone - Unlock BL + open root permission
- 第12周实验---基于FPGA的VGA协议实现
- 学习通否认 QQ 号被盗与其有关:已报案;iPhone 14 量产工作就绪:四款齐发;简洁优雅的软件早已是明日黄花|极客头条...
- Does anyone encounter this problem when flinkcdc synchronizes MySQL?
- UserWarning: Usage of dash-separated ‘script-dir‘ will not be supported in future versions. note
- 多线程高并发服务器:3个问题
猜你喜欢

活动邀请 | Apache Doris 社区征文&演讲征集活动开始了!

Spark - one to one correspondence between task and partition and detailed explanation of parameters

【NLP】文本生成专题1:基础知识

How to obtain method parameter values through WinDbg

The encryption market has exploded one after another. Can Celsius avoid bankruptcy?

Online text filter less than specified length tool

学习通否认 QQ 号被盗与其有关:已报案;iPhone 14 量产工作就绪:四款齐发;简洁优雅的软件早已是明日黄花|极客头条...

Using EasyX configuration in clion

他98年的,我玩不过他...

极限导论总结
随机推荐
The encryption market has exploded one after another. Can Celsius avoid bankruptcy?
ZABBIX monitors various MySQL indicators
Dropout layer
ModbusTCP协议网络学习型单路红外模块(双层板)
ModbusTCP协议WIFI无线学习型单路红外模块(小壳版)
nuc980 已成功启动
Modbus RTU 协议485学习型2路红外模块
Shell 中你不得不熟知的变量运用
dropout层
He was in '98. I can't play with him
最后的 48 小时!云 XR 专题赛邀你一起绽放精彩,我们赛场见!
添加通知公告,给在线用户发送通知
LVGL库入门教程 - 动画
极限导论总结
(JS)数组方法:slice和splice
【Rust每周一库】Tokei - 统计代码行数等信息的实用工具
Daily question brushing record (VII)
(JS)观察者模式
misc3~7
MySQL query table field information