当前位置:网站首页>Shell -- custom variables and assignments
Shell -- custom variables and assignments
2022-07-27 06:37:00 【m0_ sixty-nine million five hundred and ten thousand two hundre】
List of articles
One 、shell The variable of
Variables are used to temporarily store data , And the data can change from time to time , No language can do without variables , If something needs to be used more than once and will reappear , So you can use variables , If you need to modify, just modify the variable directly
common Shell The types of variables include custom variables 、 environment variable 、 A read-only variable 、 Positional variable 、 Predefined variables
1、 Custom variable
1、 Definition of variables
Bash The variable operation in is relatively simple , Unlike other high-level programming languages ( Such as C/C++、Java etc. ) So complicated . When defining a new variable , Generally, there is no need to make a statement in advance , Instead, specify the variable name directly and assign it to the initial value ( Content ) that will do
Format : Variable name = A variable's value
Variable name : A place where data is temporarily stored
A variable's value : Temporary changeable data
There is no space on either side of the equal sign . Variable names should start with letters or underscores , Do not include special characters in the name ( Such as +、-、*、/、.、?、%、&、# etc. )
2、 environment variable
Environment variable refers to the environment variable generated by Linux A type of variable created by the system in advance , It is mainly used to set the user's working environment , Include user host Directory 、 Command to find the path 、 User current directory 、 Login terminal, etc .
The value of the environment variable is determined by Linux Automatic system maintenance , It will change with the change of user state .
Use env The command can view the environment variables in the current working environment , For some common environment variables, we should understand their respective purposes .
- for example
- Variable USER Represents the user name
- HOME Represents the user's Host Directory
- LANG Represents the language and character set
- PWD Indicates the current working directory
- PATH Indicates command search path, etc
- RANDOM Represents a random number , Returns the 0-32767 The integer of
- USER Indicates the account name of the current account , It is generally defined in all uppercase , Note the distinction between and custom variables
[[email protected] ~]# echo $RANDOM # It returns a random number 20315 [[email protected] ~]# echo $RANDOM 25684 [[email protected] ~]# echo $HOME /root [[email protected] ~]# echo $USER root [[email protected] ~]# echo $UID 0 [[email protected] ~]# echo $PWD /root [[email protected] ~]# echo $LANG zh_CN.UTF-8 [[email protected] ~]# echo $SHELL /bin/bash
3、PATH Variable
PATH Variable is used to set the default search path for the executable program , When only the file name is specified to execute the command program ,Linux The system will be in PATH Variable to find the corresponding executable file , If it cannot be found, it will prompt “command not found”.
[[email protected] ~]# test.sh
bash: test.sh: Command not found ...
[[email protected] ~]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
[[email protected] ~]# pwd
/root
This is because test.sh be not in $PATH In the directory of , So the system can't recognize it and can't use it directly , You need to keep up with the absolute path and use the script
Method 1 : Add the directory of the script to $PATH
[[email protected] ~]# PATH="$PATH:/root" # This is temporary , If it takes effect permanently, you need to edit /etc/profile file
[[email protected] ~]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/root
[[email protected] ~]# test.sh
hello world
Method 2 : Put your own script into $PATH A directory in
stay Linux In the system , The global configuration file of the environment variable is /etc/profile, The variables defined in this document act For all users . besides , Each user also has its own independent configuration file (~/.bash_profile).
After the modification, you have to log in again to take effect , If you want to take effect immediately , have access to source
4、 A read-only variable
Shell There is a special case in variables , Once set , Its value is unchangeable , This variable is called a read-only variable The amount . When you create a variable, you can set it as a read-only property , You can also set an existing variable as a read-only property , only Reading variables is mainly used when the value of variables cannot be modified
Read only variables cannot be changed or deleted
[[email protected] ~]# test=123
[[email protected] ~]# readonly test #readonly Used to define read-only variables , Once the use readonly Defined variables cannot be changed in a script
[[email protected] ~]# echo $test
123
[[email protected] ~]# test=456
-bash: test: A read-only variable
[[email protected] ~]# unset test
-bash: unset: test: Can't reset : read-only variable
Methods for deleting read-only variables : Exit the account to refresh the memory , Eliminate variables !!!
[[email protected] ~]# exit Log out Connection closed. Disconnected from remote host(centos7-2) at 22:38:32. Type `help' to learn how to use Xshell prompt. [C:\~]$ Connecting to 192.168.226.127:22... Connection established. To escape to local shell, press 'Ctrl+Alt+]'. Last login: Fri Jul 1 22:38:22 2022 from 192.168.226.1 [[email protected] ~]# echo $teat ## Will display as empty [[email protected] ~]#
5、 Positional variable
When performing command line operations , The first field represents the command name or script program name , The remaining string parameters are assigned to the position variable in order from left to right .
Location variables are also called location parameters , Use $1、$2、$3、…、$9 Express
The name of the command or script itself uses “$0” Express
example : Write a simple script to create users and passwords
[[email protected] ~]# vim 1.sh
#!/bin/bash
useradd $1
echo $2 | passwd --stdin $1
[[email protected] ~]# bash 1.sh ct 123
Change user ct Password .
passwd: All authentication tokens have been successfully updated .
[[email protected] ~]#
[[email protected] ~]# id ct
uid=1001(ct) gid=1001(ct) Group =1001(ct)
6、 Predefined variables
The predefined variables are created by Bash A class of special variables pre-defined by a program , Users can only use predefined variables , and Cannot create a new predefined variable , You can't assign values to predefined variables directly . Predefined variables use “$” A combination of a symbol and another symbol indicates
| Variable | meaning |
|---|---|
| $# | Indicates the number of positional parameters in the command line |
| $* | Represents the contents of all positional parameters , These contents as a whole |
| [email protected] | Indicates that all position parameters are listed , But it is listed in a single form |
| $? | Indicates the return status after the execution of the previous command , The return value is 0 The execution is correct , Return any non 0 Values indicate an exception in execution |
| $0 | Indicates the name of the currently executing script or program |
| $$ | Indicates that the process number of the current process is returned |
| $! | Returns the process number of the last background process |
example 1: Understand the meaning of each predefined and location variable according to a simple script
#!/bin/bash
echo $1
echo “$0 Indicates the name of the currently executing script or program ”
echo “$# Indicates the number of positional parameters in the command line ”
echo “$* The contents of all positional parameters , These contents as a whole ”
echo “[email protected] Indicates that all position parameters are listed , But it is listed in a single form ”
understand $* and [email protected] The difference between
$*、[email protected]: Represents the parameters to be processed by a command or script .
$*: Think of all parameters as a whole string separated by spaces ( Single string ) return , representative "$1 $2 $3 $4".
[email protected]: Separate each parameter with double quotation marks into n A list of the parameters of the , Each parameter is returned as a string , representative "$1""$2""$3""$94".
7、 Define variables interactively
read command
Options
Options meaning -p Information to prompt users -n Define the number of characters -s Don't show user input , Commonly used to enter passwords read -s -p “input your password:” pass -t Define timeout , If you haven't lost for more than a long time, you will automatically quit
In addition to the above assignment operations , You can also use Bash Built-in commands read To assign a value to a variable .
Used to prompt the user to enter information , So as to realize a simple interactive process . It will be executed from the standard input device ( keyboard ) Read in One line , And use a space as a separator , Assign the read fields to the specified variable in turn ( Assign extra content to The last variable ). If only one variable is specified , Assign the entire line to this variable .
[[email protected] ~]# read date
4 # Waiting for user input , Assign the entered value to test Variable
[[email protected] ~]# echo $date
4
Generally speaking, in order to make the interface of interactive operation more friendly , Improve ease of use ,read Commands can be combined with “-p” Option to set the prompt message , In order to inform the user what content to enter and other related matters
[[email protected] ~]# read -p " Today, this week " date
Today, this week 4
[[email protected] ~]# echo " Today, this week $date"
4
- contrast
[[email protected] ~]# read " week " date
4
-bash: read: ` week ': Not a valid identifier
[[email protected] ~]# read -p " week " date
week 4
[[email protected] ~]# echo "$date"
4
It can be seen that it is used alone read The command cannot use Chinese characters
use read -p Chinese characters can be quoted
Action range of variable
By default , The newly defined variable is only in the current Shell Effective in the environment , So it's called a local variable , When entering a subroutine or a new subroutine Shell Environmental time , Local variables will no longer be used
[[email protected] ~]# bash # Intron shell Environmental Science
[[email protected] ~]#
[[email protected] ~]# echo $name
# The display is empty
Two 、 View and reference the values of variables
use echo View and reference the values of variables
By adding a leading symbol before the variable name “$”, You can reference the value of a variable , Use echo Command can view variables , Can be in one echo View multiple variable values at the same time in the command
for example
[[email protected] ~]#Product=Python
[[email protected] ~]#Version=2.7.13
[[email protected] ~]#echo $Product$Version
Python2.7.13
When variable names are easily confused with other characters immediately following them , You need to add braces “{}” Enclose it , Otherwise, the correct variable name cannot be determined . For undefined variables , Will be displayed as a null value
give an example#{} Reference variables echo ${Product}2.5 2.5 echo ${test}RMB RMB
echo Options
echo -n Indicates no line feed output
- Use echo -e Output escape characters , Output the escaped content to the screen
The commonly used escape characters are as follows :
\c Don't wrap output , stay ”\c” If there are no characters after , The effect is equivalent to echo -n
\n Line break
\t After escape, it means to insert tab, That's the tab
notes :\ Escape character , With the \ The special symbol after that will lose its special meaning , Change to normal characters . Such as "\ $" Will output “ $” Symbol , Improper doing is variable reference
example
[[email protected] ~]# echo -n hello
hello[[email protected] ~]#
[[email protected] ~]# echo -e "hello\t"
hello
Undefine
unset Variable name
3、 ... and 、 Special operations
There are also some special assignment operations , You can assign values to variables more flexibly , So as to be applicable to various complex management tasks
1、 Double quotes : " "
Double quotation marks are mainly used to define strings , Especially when the content to be assigned contains spaces , Must be enclosed in double quotation marks ; In other cases, double quotation marks can usually be omitted
1、 When there are spaces in the content
echo “hello world”
echo nihao
2、 When the value of a variable is assigned
[[email protected] ~]# version=2
[[email protected] ~]# pyver="python $version"
[[email protected] ~]# echo $pyver
python 2
2、 Single quotation marks : ‘’
When the content to be assigned contains "$、“、”" And other characters with special meaning , Should be enclosed in single quotation marks .
Within single quotation marks , You will not be able to reference the values of other variables , Any character is treated as a normal character . Display what you enter
But the assignment content contains single quotation marks (‘) when , Need to use \’ The symbols are escaped , To avoid conflict .
[[email protected] ~]# test=123
[[email protected] ~]# echo "$test"
123
[[email protected] ~]# echo '$test'
$test
3、 Apostrophe : ``
The apostrophe is mainly used for command substitution , Allows you to assign the screen output result of executing a command to a variable .
The range enclosed by the apostrophe must be an executable command line , Otherwise, there will be mistakes
ls -lh `which useradd`
Through the first which useradd Command to find out useradd The program location of the command , Then list the file attributes according to the search results
[[email protected] ~]# time=`date +%T`
[[email protected] ~]# echo $time
04:23:22
It is difficult to implement nested command substitution in one line of command by using apostrophe , At this time, you can use “$()” Instead of the apostrophe operation , To solve the problem of nesting
for example
[[email protected] ~]# rpm -qc `(rpm -qf `(which useradd)`)`
-bash: Unexpected symbols `(' There are grammar errors nearby
[[email protected] ~]# rpm -qc `(rpm -qf $(which useradd))`
/etc/default/useradd
/etc/login.defs
[[email protected] ~]# rpm -qc $(rpm -qf $(which useradd))
/etc/default/useradd
/etc/login.defs
- From that `` Symbols cannot nest instructions ,$() Can be nested
Four 、export command
In order to make user-defined variables in all sub variables Shell Can continue to be used in the environment , Reduce duplicate setup work , It can be done by internal command export Exports the specified variable as a global variable . You can specify multiple variable names as parameters at the same time ( No need to use “$” Symbol ), Variable names are separated by spaces
[[email protected] ~]# exit
exit
[[email protected] ~]# export name test
[[email protected] ~]# bash
[[email protected] ~]# echo "$name $test"
Zhang San 123
Use export While exporting global variables , You can also assign values to variables , In this way, when the global variable is newly defined, there is no need to assign a value in advance
env View the user's current environment variables
export ABC=123
Again env You can see it
export -n ABC Undefined global variables become local variables
边栏推荐
猜你喜欢
随机推荐
Using markdowm
If conditional statement of shell
源码编译安装LAMP和DISCUZ论坛
Li Kou daily question leetcode 513. find the value in the lower left corner of the tree
C language - Custom structure type
Shell脚本编写格式
C language - file operation
数据库在终端的基础操作
数据库的索引和事务(重点)
Basic file operation of cmder
数组及下标索引
Markdown文档常用字体及颜色设置
Wireshark packet modification -- adding or modifying message fields (2)
shell--自定义变量与赋值
jmeter简介
Launch file of ROS operation management
ROS node name duplicate
Unit integration (grounding) test
Interpretation of unity desktop version 7.6
Navigation related messages








