当前位置:网站首页>Practical shell knowledge
Practical shell knowledge
2022-07-01 01:06:00 【Look, the future】

Put this picture , Nothing else .
List of articles
Basic knowledge of
./XXX.sh
It works like this
Shell Variable
your_name="XXX"
1、 There can be no spaces between variable names and equal signs .
2、 Only English letters can be used for naming , Numbers and underscores , The first character cannot begin with a number .
3、 No spaces in between , You can use underscores _.
4、 You can't use punctuation .
5、 Out of commission bash Keywords in ( You can use help Command to view reserved keywords ).
Using variables
Use a defined variable , Just precede the variable name with a dollar sign , Such as :
your_name="qinjx"
echo $your_name
echo ${
your_name}
Maybe one day you'll see someone who didn't add ${}, Don't be surprised .
Shell character string
The string is shell The most commonly used and useful data types in programming ( Besides numbers and strings , There is no other type to use ), Strings can be in single quotes , You can also use double quotes , You can also use no quotes .
Single quotation marks
str='this is a string'
Restrictions on single quoted 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
your_name="runoob"
str="Hello, I know you are \"$your_name\"! \n"
echo -e $str
The output is :
Hello, I know you are "runoob"!
The advantages of double quotes :
You can have variables in double quotes
Escape characters can appear in double quotes
String concatenation
your_name="runoob"
# Using double quotation marks
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
echo $greeting $greeting_1
# Using single quotation marks
greeting_2='hello, '$your_name' !'
greeting_3='hello, ${your_name} !'
echo $greeting_2 $greeting_3
The output is :
hello, runoob ! hello, runoob !
hello, runoob ! hello, ${your_name} !
Get string length
string="abcd"
echo ${
#string} # Output 4
Extract substring
The following example starts from the string No 2 Characters begin to intercept 4 Characters :
string="runoob is a great site"
echo ${string:1:4} # Output unoo
Shell Array
stay Shell in , Use parentheses to represent arrays , For array elements " Space " Symbol split . The general form of defining an array is :
Array name =( value 1 value 2 ... value n)
for example :
array_name=(value0 value1 value2 value3)
perhaps
array_name=(
value0
value1
value2
value3
)
You can also define the components of an array separately :
array_name[0]=value0
array_name[1]=value1
array_name[n]=valuen
Can not use consecutive subscripts , And there is no limit to the scope of subscripts .
Read array
The general format for reading array element values is :
${ Array name [ Subscript ]}
Use @ The symbol can get all the elements in the array
echo ${array_name[@]}
Gets the length of the array
The way to get the array length is the same as the way to get the string length , for example :
# Get the number of array elements
length=${
#array_name[@]}
# perhaps
length=${
#array_name[*]}
# Get the length of a single element of an array
lengthn=${
#array_name[n]}
Shell notes
With # The first line is the comment , Will be ignored by the interpreter .
Multiline comments can also use the following format :
:<<EOF The comment ... The comment ... The comment ... EOF
EOF You can also use other symbols :
:<<' The comment ... The comment ... The comment ... '
Shell Pass parameters
We can execute Shell Script time , Pass parameters to script , The format of obtaining parameters in the script is :$n.n Represents a number ,1 For executing the first parameter of the script ,2 For executing the second parameter of the script , And so on ……
echo "Shell Pass parameter instance !";
echo " File name of execution :$0";
echo " The first parameter is zero :$1";
echo " The second parameter is :$2";
echo " The third parameter is zero :$3";
$ ./test.sh 1 2 3
in addition , There are also a few special characters used to pass parameters :
Operator
Relational operator

Logical operators

String operators

File test operators

echo
For string output .
echo string
echo "It is a test"
echo -e "OK! \n" # -e Open escape
echo "It is a test"
Process control
Branch
Judge whether the execution of the previous statement is successful :
shell Using symbols in “$?” To display the return value of the last command execution , If 0 On behalf of the successful implementation , Other indication of failure .
if [ $? -ne 0 ]; then
echo "failed"
else
echo "succeed"
fi
if condition
then
command1
command2
...
commandN
fi
if condition
then
command1
command2
...
commandN
else
command
fi
if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
for loop
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
Write in a line :
for var in item1 item2 ... itemN; do command1; command2… done;
When variable values are in the list ,for A loop executes all the commands at once , Use the variable name to get the current value in the list . The command can be any valid shell Commands and statements .in The list can contain substitutions 、 String and file name .
in List is optional , If you don't use it ,for Loop through the positional parameters of the command line .
while sentence
while Loop is used to execute a series of commands continuously , Also used to read data from the input file . Its grammatical form is :
while condition
do
command
done
Out of the loop
During the cycle , Sometimes it's necessary to force the loop out before the loop end condition is reached ,Shell Use two commands to do this :break and continue.
break command
Shell Input / Output redirection

Practical script collection
Determine whether the instruction is successfully executed
if [ $? -ne 0 ]; then
echo "failed"
else
echo "succeed"
fi
I have been using this today , Because the log must be written for successful or unsuccessful execution , And write logs separately .
Whether the batch test file exists
[[email protected] ~]# cat testfile.sh
#!/bin/bash
for file in test*.sh
do
if [ -f $file ];then
echo "$file existed."
fi
done
[[email protected] ~]# ./testfile.sh
test.sh existed.
test1.sh existed.
test2.sh existed.
test3.sh existed.
test4.sh existed.
test5.sh existed.
test78.sh existed.
test_dev_null.sh existed.
testfile.sh existed.
Supplement after use .
边栏推荐
- NE555 waveform generator handle tutorial NE555 internal structure (I)
- HDU 2488 A Knight's Journey(DFS)
- What is the difference between Pipeline and Release Pipeline in azure devops?
- History of deep learning
- CMU15445 (Fall 2019) 之 Project#1 - Buffer Pool 详解
- Stack frame
- Redis based distributed lock
- 2022-2028 global ultra high purity electrolytic iron powder industry research and trend analysis report
- 2022-2028 global single travel industry research and trend analysis report
- Vnctf 2022 cm CM1 re reproduction
猜你喜欢

Gavin's insight on the transformer live broadcast course - rasa project's actual banking financial BOT Intelligent Business Dialogue robot system startup, language understanding, dialogue decision-mak

The quantity and quality of the devil's cold rice 101; Employee management; College entrance examination voluntary filling; Game architecture design

Oracle temporary table explanation

Authentication principle of Ranger plug-in

Implementation of date class

From January 11, 2007 to January 11, 2022, I have been in SAP Chengdu Research Institute for 15 years

Oracle data integrity

Cmu15445 (fall 2019) project 1 - buffer pool details

2022-2028 global herbal diet tea industry research and trend analysis report

酒旅板块复苏,亚朵继续上市梦,距离“新住宿经济第一股“还有多远?
随机推荐
2022-2028 global capsule shell industry research and trend analysis report
20220216 misc buuctf backdoor killing (d shield scanning) - clues in the packet (Base64 to image)
Tcp/ip protocol stack, about TCP_ RST | TCP_ ACK correct attitude
酒旅板块复苏,亚朵继续上市梦,距离“新住宿经济第一股“还有多远?
CSDN常用复杂公式模板记录
Oracle临时表详解
2022-2028 global ICT test probe industry research and trend analysis report
20220215 misc buctf easycap Wireshark tracks TCP flow hidden key (use of WinHex tool)
连表查询 select 生成
How to scroll uitableview to a specific position - how to scroll uitableview to specific position
PHP online confusion encryption tutorial sharing + basically no solution
Oracle-数据完整性
From January 11, 2007 to January 11, 2022, I have been in SAP Chengdu Research Institute for 15 years
Vnctf 2022 cm CM1 re reproduction
What should I do without 50W bride price
实验八 T-sql,存储过程
What is the difference between Pipeline and Release Pipeline in azure devops?
Golang treasure house recommendation
Day31-t1380-2022-02-15-not answer by yourself
Can JDBC based on openjdk connect to MySQL?