Linux shell basic syntax

Time:2021-3-4

Wu Hongdong – recorded on July 3, 2018 – bloghttps://segmentfault.com/u/wu…

Linux shell basic syntax

script

sign

#! / bin / Bash is the first line of the shell script, which indicates what interpreter the script uses;

#!/bin/bash

Echo command is used to output text to the window;

echo "hello shell";
#Turn on escape wrap
echo -e "hello \n shell";
#Back quotation marks show the result of command execution
echo `ls /`;
#Direct the display results to a file
echo 'hello' > 1.txt;

Single-Line Comments

#Represents a single line comment;

For multiline comments, EOF can also use other symbols, such as!

:>>EOF  
Note 1 
Note 2
EOF

:>>!
Note 1 
Note 2
!

example

Create a script file named / tmp/ hello.sh

#!/bin/bash
echo "hello shell";

Give the script execution permission to execute the script

chmod u+x /tmp/hello.sh;
./tmp/hello.sh

variable

Define usage

Format: key = value;
When value is in single or double quotation marks, it is a string; when it is a number, it is a numerical type;
The standard format is ${key}, but sometimes $key; can be used for reference;

#String variable
a='A';
b="${a}\B";
#Read only variable
readonly c=7;
#Global variables
export d=3.14;
#The content of single quotation marks will be output as is, and single quotation marks and escape characters cannot be used
echo $a;
#Double quotation content can contain variables and escape characters can be used
echo $b;
#Delete variable
unset c;

character string

n="0123456789";
m="aaabbbaaabbb";
#Returns the length of the string variable n
echo ${#n};
#Returns the part from the fifth character to the last
echo ${n:5};
#Returns the length of 5 starting from the 0 th character
echo ${n:0:5};
#Delete the part whose beginning matches 012
echo ${n#012};
#Delete the end that matches 789
echo ${n%789};
#Replace the first AAA with XXX
echo ${m/aaa/xxx};
#Replace all AAA with XXX
echo ${m//aaa/xxx};
#Replace AAA at the beginning with XXX
echo ${m/#aaa/xxx};
#Replace BBB at the end with XXX
echo ${m/%aaa/xxx};

Execution output:

10
56789
01234
3456789
0123456
xxxbbbaaabbb
xxxbbbxxxbbb
xxxbbbaaabbb
aaabbbaaabbb

Replace extension

v=V;
echo $v;
#If V is undefined or null, VVV is returned, but the value of V remains unchanged; if V exists and is not null, V is returned;
echo ${v:-vvv};
#If V is undefined or null, VVV is returned and the value of V is assigned VVV; if V exists and is not null, V is returned;
echo ${v:=vvv};
#If V is undefined or null, VVV is returned and the script is terminated; if V exists and is not null, V is returned;
echo ${v:?vvv};
#If V is undefined or null, it returns null, but the value of V remains unchanged; if V exists and is not null, it returns VVV;
echo ${v:+vvv};

Numerical operation

Four operators: +, -, */
Power operator, module operator: * *,%
Auto increment and auto decrement operators: + +–
Assignment operators: =, + =, – =, * =, / =,%=
Comparison operators: <, >, < =, > =, = ==
Logical operators: & &, |!

#Operation expression must be in double brackets ((expression))
Echo $((a = 3 * * 2)); # output 9

Variable input

Format: read – P < Prompt string > [< variable name >…];

#Enter a single variable
Read - P "please input:" n;
echo $n;
#Enter multiple variables
Read - P "please input:" N1 N2 N3;
echo $n1 / $n2 / $n3;

Return value

Each command will return a status code, 0 indicates success, other non-zero values indicate various errors, exit n; (n ranges from 0 to 255), 1 indicates general error, 126 indicates no execution permission, 127 indicates command not found;

parameter

Chuanshen

Format:. / shell script file parameter 1 Parameter 2

#Add to script file test.sh Three parameters are involved
./shell/test.sh p1 p2 p3;
# test.sh Get parameters in file
echo $1 $2 $3;

Get the reference

#The number of parameters passed to the script
echo $#;
#Show all parameters
echo $*;
echo [email protected];
#Display the first parameter
echo $1;
#Display the 10th parameter, which must use ${n} from the 10th parameter
echo ;
#The exit status of the last command is displayed. 0 means no error, and other values mean error;
echo $?;
#PID of current process
echo $$;

Test expression

Test statement

Format 1: Test < test expression >
Format 2: [< test expression >]
Format 3: [[< test expression >]]
Format 1 is equivalent to format 2, and format 3 can use the logical connectors of &, |;
Spaces must be left before and after the symbols of format 2 and 3;

a=1.1;
b=1.1;
if test $a == $b; then
# if (( $a == $b )); then
# if [ $a -eq $b ]; then
# if [[ $a == $b ]]; then
Echo 'equal';
fi;

String test

-Whether the Z STR string is empty;
-N whether the str string is non empty;
STR1 = = STR2 whether the two strings are the same;
STR1! = STR2 whether the two strings are different;

Binary comparison of integers

Use – EQ, – Ne, – GT, – Ge, – LT, – Le in;
(()) use = =,! =, >, > =, <, < =;
Use – A, – O!;
[]]!;

File directory test

-Whether e-file exists or not;
-F file is a normal file;
-D whether the file is a directory;
-Whether l file is a link file;
-B whether the file is a block device file;
-Whether C file is a character device file;
-Whether s file is non-zero and non empty;
-Whether R file is readable or not;
-Whether w file is writable;
-Whether x file is an executable file;
-Whether o file is the owner of the file;
-Whether g file is the file group;
-Whether the permission of suid is set in U file;
-Whether sgid permission is set in G file;

#Create a directory when it does not exist
[ !-e /shell ] && mkdir -p /shell;

array

definition

Format 1: array = (A1 ‘A2’ A3);
Format 2: array [0] = A1; array [1] =’a2 ‘; array [2] = A3;

#Define array
array=(1 '2');
#Set the third element
array[2]=3;
#Show first element
echo array[0];
#Gets all the elements of the array
echo ${array[*]};
echo ${array[@]};
#Gets the size of the array
echo ${#array[*]};

function

definition

Format: function fun() {}
Function keyword can be omitted;
Return n can be added; (n must be 0 ~ 255) after the function is executed, the return value can be obtained through $;

fun() {
    return 1;
    echo 'over';
}
fun;
echo $?;

Process control

If statement

if test -e /shell/1; then
    Echo '1 file exists';
elif test -e /shell/2; then
    Echo '2 file exists';
#The else branch is the last default branch, which can be omitted and can only be one at most
else 
    Echo 'does not exist';
fi;

Case statement

Read - p 'please enter:' num;
case $num in
1) echo 'num=1' ;;
2) echo 'num=2' ;;
*) echo 'num=?' ;;
esac

While statement

Break: jump out of the cycle;
Continue: skip this cycle and enter the next iteration;
Exit n: aborts the current function and the main shell that calls it;

i=0;
len=10;
while (($i < $len));do
    echo $i;
    let "i++";
done;
#Loop read file line content
while read line;
do
    echo $line;
done < /shell/proxy;
#Or
cat /shell/proxy | while read line;
do
    echo $line;
done;

Until statement

In contrast to while, until ends the loop when the return value is 0;

For statement

#Literal constant list
for loop in 1 2 3 4 5;
do
    echo "The value is: $loop"
done;
#Parameter list, in [email protected] can be omitted
for p in [email protected];
do
    echo $p;
done;
#Sequence list
for x in {1..9};
do
    echo $x;
done;
#C-type for loop
for((i=0;i<10;i++)) {
    echo $i;
}

Select statement

Select is a menu loop structure, infinite loop, exit can add break or press < Ctrl + C >, generally add case statement processing;

select x in 1 2 3;
do
    case $x in 
    1) echo 'x=1' ;;
    *) echo 'x=?' ;; 
    esac;
done;

Infinite cycle

while :
#Or while true
do
    echo 'loop';
done;
for(( ; ; )){
    echo 'loop';
}

Recommended Today

Third party calls wechat payment interface

Step one: preparation 1. Wechat payment interface can only be called if the developer qualification has been authenticated on wechat open platform, so the first thing is to authenticate. It’s very simple, but wechat will charge 300 yuan for audit 2. Set payment directory Login wechat payment merchant platform( pay.weixin.qq . com) — > Product […]