当前位置:网站首页>Shell scripts: Variables
Shell scripts: Variables
2022-06-25 20:50:00 【zzy570384336】
Knowledge points encountered in learning , Make a note .
#! Tell the system that the executable program behind it is to explain how to run this script shell
Such as
#!/bin/sh
#1/bin/bash
Variable
Variable naming
Variable naming must follow the following rules
Only English letters can be used for naming , Numbers and underscores , The first character cannot begin with a number .
No spaces in between , You can use underscores _.
You can't use punctuation .
Out of commission bash Keywords in ( You can use help Command to view reserved keywords ).
Using variables
When defining variables , There must be no space between the variable name and the equal sign .
When using variables, you only need to add $ A symbol is enough
Such as :
test_var="hello"
echo $test_var
echo ${test_var}
Outside variable name {} To better distinguish the boundaries of variable names
Variable type
function shell when , Divided by variable scope , There will be three variables at the same time :
- local variable Local variables are defined in scripts or commands , At present only shell Valid in instance , other shell Started program cannot access local variables .
- environment variable All procedures , Include shell Program started , Can access environment variables , Some programs need environment variables to ensure their normal operation . When necessary shell Scripts can also define environment variables .
- shell Variable shell Variables are derived from shell Special variables for program settings .shell Some of the variables are environment variables , Some of them are local variables , These variables guarantee shell Normal operation of
A read-only variable
readonly The command can change a variable to a read-only variable , Read only variables can only be read , Do not modify
Example
echo ${string}
string="abcd"
echo ${string}
string="dcba"
echo ${string}
readonly_string="abcd"
echo ${readonly_string}
readonly readonly_string
readonly_string="dcba"
echo ${readonly_string}
Output
abcd
dcba
abcd
./test.sh: line 9: readonly_string: readonly variable
abcd
You can see when , An error will be reported when you want to change a read-only variable , And the modification is invalid
Delete variables
Use command unset You can delete variables , This command cannot delete read-only variables
echo ${string}
string="abcd"
echo ${string}
unset string
echo ${string}
readonly_string="abcd"
echo ${readonly_string}
readonly readonly_string
unset readonly_string
echo ${readonly_string}
Output :
abcd
abcd
./test.sh: line 10: unset: readonly_string: cannot unset: readonly variable
abcd
character string
Single quotation marks
str='this is a string'
Any character in a single quotation mark will be output as is , Variables in a single quoted string are invalid ;
A single quotation mark cannot appear in a single quotation mark string ( You can't escape a single quotation mark ), But in pairs , Use as string concatenation .
Double quotes
#!/bin/bash
test_word="world"
str="Hello, \"${test_word}\"! \n"
echo -e ${str}
The output is
Hello, "world"!
You can have variables in double quotes
Escape characters can appear in double quotes
echo Of -e Parameters are used to handle \n And other special function characters , If you do not add \n Will print as is .
Such as :
Hello, "world"! \n
String splicing
#!/bin/bash
test_word="world"
str1="Hello, "${test_word}"! \n"
echo -e str1 ${str1}
str2="Hello, '${test_word}'! \n"
echo -e str2 ${str2}
str3="Hello, ${test_word}! \n"
echo -e srt3 ${str3}
str4='Hello, "${test_word}"! \n'
echo -e str4 ${str4}
str5='Hello, '${test_word}'! \n'
echo -e str5 ${str5}
str6='Hello, ${test_word}! \n'
echo -e str6 ${str6}
str7='Hello, '${test_word}
echo -e str7 ${str7}
str8='Hello, '"world! \n"
echo -e str8 ${str8}
Output
str1 Hello, world!
str2 Hello, 'world'!
srt3 Hello, world!
str4 Hello, "${test_word}"!
str5 Hello, world!
str6 Hello, ${test_word}!
str7 Hello, world
str8 Hello, world!
From above 7 For example, we can conclude that :
1. In a string in double quotation marks , Variables can be referenced directly , Single quotation marks don't work , Such as str3,str6;
2. The single quotation mark in the string with double quotation marks will be printed as is , The same is true of double quotation marks in single quotation marks , Such as str2,str4;
3. Two strings will be spliced together , Whether in double or single quotation marks , Or variables , Such as str1、str5、str7、str8.
Get string length
string="abcd"
echo ${
#string} # Output 4
Extract substring
string="test abcd"
echo ${string:5:9}
# Output
abcd
Note the serial number from 0 Start
Find substrings
lookup ba The first character to appear in
string="test abcd"
index=`expr index "${string}" "ba"` #` It's a back quote , Not single quotes '
echo ${index} # Output 6, because a stay b Appear before
Array
shell Support array , Only one-dimensional arrays are supported , Multidimensional arrays are not supported .
shell The array in is similar to c Language , The subscript of array element is from 0 Numbered starting , To get the elements in the array, you need to reference the subscript , The referenced subscript can be an integer or an arithmetic expression , Its value should be greater than or equal to 0.
Define an array
shell Use parentheses in () To represent an array , Array element use “ Space ” Separate . The general form of defining an array is :
Array name =( Elements 1 Elements 2 Elements 3 Elements 4 ... Elements n)
# perhaps
Array name =(
Elements 1
Elements 2
Elements 3
Elements 4
...
Elements n
# Or define the components of each element in the array separately , Discontinuous subscripts can be used , And the range of subscripts is unlimited
Array name [0]= Elements 1
Array name [1]= Elements 2
...
Array name [n-1]= Elements n
)
Read array
The general format for reading array elements is
${ Array name [ Subscript ]}
have access to @ perhaps * Instead of subscript, get all the elements in the array
${ Array name [@]}
${ Array name [*]}
array1=(0 1 2 3)
echo ${array1[0]}
echo ${array1[3]}
echo ${array1[@]}
echo ${array1[*]}
array2=(0
1
2
3)
echo ${array2[0]}
echo ${array2[3]}
echo ${array2[@]}
echo ${array2[*]}
array3[0]=0
array3[3]=3
echo ${array3[0]}
echo ${array3[3]}
echo ${array3[@]}
echo ${array3[*]}
Output
0
3
0 1 2 3
0 1 2 3
0
3
0 1 2 3
0 1 2 3
0
3
0 3
0 3
Gets the length of the array
Getting the length of an array is the same as getting the length of a string .
array[0]="123"
array[3]="345"
echo ${
#array[@]}
echo ${
#array[*]}
echo ${
#array[3]}
Output
2
2
3
notes
Annotated code does not execute
Single-line comments
Use # Add to the beginning of a line for a single line comment
# This is a line of comments
# echo "123"
Multiline comment
:<<!
array1=(0 1 2 3)
echo ${array1[0]}
echo ${array1[3]}
!
echo ${array1[@]}
echo ${array1[*]}
Use
:<< character
character
To annotate multiple lines , The symbol can be any character or symbol (< With the exception of )
边栏推荐
- Node connection MySQL
- Redis core principle and design idea
- Literals and type conversions of basic data types
- Lesson 4 beautifulsoup
- Causes and solutions of unreliable JS timer execution
- HMS core actively explores the function based on hardware ear return, helping to reduce the overall singing delay rate of the singing bar by 60%
- Yanjiehua, editor in chief of Business Review: how to view the management trend of business in the future?
- How to view and explain robots protocol
- Log4j2 vulnerability battle case
- Installing mysql8 under centos8
猜你喜欢
Boomfilter learning
CSDN sign in cash reward
Detailed explanation of unified monitoring function of multi cloud virtual machine
"Space guard soldier" based on propeller -- geosynchronous geostationary orbit space target detection system
Introduction to the basics of kotlin language: lambda expression
Log4j2 vulnerability battle case
Cloud native 04: use envoy + open policy agent as the pre agent
Share a billing system (website) I have developed
Splunk series: Splunk data import (II)
R language momentum and Markowitz portfolio model implementation
随机推荐
Is it safe for qiniu school to open an account in 2022?
How does zhiting home cloud and home assistant access homekit respectively? What is the difference between them?
Section 13: simplify your code with Lombok
COMP9024
Introduction to event flow, event capture, and event bubbling
Global netizens Yuanxiao created a picture of appreciating the moon together to experience the creativity of Baidu Wenxin big model aigc
Node installation method you don't know
Modifying routes without refreshing the interface
JS canvas drawing an arrow with two hearts
Getting started and using postman
"Space guard soldier" based on propeller -- geosynchronous geostationary orbit space target detection system
1.1-mq visual client preliminary practice
A simple file searcher
Teach you how to create and publish a packaged NPM component
Exploration of advanced document editor design in online Era
How to buy the millions of medical insurance for children? How much is it a year? Which product is the best?
Insert and update each database
Sonar series: continuous scanning through Jenkins integrated sonarqube (IV)
Jingxi Pinpin wechat applet -signstr parameter encryption
Svn various color states