The most complete Linux Shell detailed tutorial

1. Environmental preparation

We are here to test and learn locally, so I do not recommend that you rush to buy a server to learn, it will be more expensive. After we have learned these basics, we will start to use the server, it will be easy. Local learning tool: virtual machine If you don’t have this tool, please install it as follows: virtual machine installation and configuration tutorial  Of course, if you have money, you can also rent one from Alibaba Cloud or Tencent Cloud.

Two, hello Linux

Create a shell script, name it test, and format it as .sh

touch test.sh

Edit script:

vim test.sh

If you don't know how to use vim, or your virtual machine does not have vim installed, read the previous part of this article: cat detailed tutorial By the way, you can also learn the cat command. Here is a rough demonstration: First enter the following command and press Enter

vim test.sh

Press the letter i key to edit, I will enter hello Linux, you can also write other content, not necessarily in English

After editing the content, press the ESC key, and then enter: wq! (meaning forced to save and exit), and press Enter.

As above, the save is successful.

3. Run the shell script

First grant permission:

chmod 777 test.sh

Execute the script:

./test.sh

Demo:

Four, shell variables

1) Ordinary variables

The variables are very simple. For example, if I want to assign the value of "Chuan Chuan handsome guy" to the variable a, it is:

a="川川帅哥"

What about using print variables?

echo $a

You can understand echo here as python's print, c language's printf, and the like.

Now we still create a new sh to test

touch test1.sh

edit file:

vim test1.sh

The edited content is as follows:

The operation interface is as follows:

As you can see, I started to forget to give the file permissions, so when I execute it, it shows that the permissions are not enough. So don't forget to give permission.

2) Read-only variables

Use the readonly command to define a variable as a read-only variable, and the value of the read-only variable cannot be changed. for example. Create new file and edit:

The edited content is as follows:

Execution will report an error:

In fact, we generally don't use such variables very much. I personally think that it is enough to understand them.

3) Delete the variable

Using the function unset is the same as the above operation, so it will not be demonstrated, it is just for understanding.

c="川川菜鸟"
unset c
echo $c

Executing the above example will produce no output.

5. Shell string

1) single and double quotes

Strings can use single quotes, double quotes, or no quotes. Create content as:

a='川川菜鳥'
b="川川帥哥"
echo $a
echo $b

Demo:

Full demo:

Single quote features:

  • Any characters in single quotes will be output as they are, and variables in single quote strings are invalid;
  • A single single quotation mark cannot appear in a single quotation mark string (even after using an escape character for the single quotation mark), but it can appear in pairs and used as a string concatenation.

Features of double quotes:  - There can be variables in double quotes - Escape characters can appear in double quotes

2) String concatenation

a="chuan"
b="chuan"
c=" $a$b"
echo $c

as follows:

The full demo is as follows:

3) Get the string length

Add echo ${#c} on top of the above:

a="chuan"
b="chuan"
c=" $a$b"
echo $c
echo ${#c}

Full demo:

4) String extraction

We can add a little more on the previous basis. We mainly use the method of slicing to obtain it. What is slicing? If you have learned python with me, then you don't know it, so I won't explain it. Edit and save the content as follows

a="chuan"
b="chuan"
c=" $a$b"
echo $c
echo ${#c}
echo ${a:1:3}

Right now:

Full demo:

6. Shell array

1) Read the index array

Shell arrays are represented by parentheses, and elements are separated by space symbols. The content of the sh file is:

a=(A B "C" D)
echo $a

Right now

The full demo is:

But are you wondering if you only output the first one? In the shell, we cannot directly output all of them like other languages, so we need to modify it. Change it to this:

a=(A B "C" D)
echo ${a[0]}
echo ${a[1]}
echo ${a[2]}
echo ${a[3]}

Save and run again:

2) Get all elements in the array

What if you want to output all at once, but don't want to output through the index? Use @ or * to get all the elements in the array. On the basis of the above, I will edit and add two lines:

a=(A B "C" D)
echo ${a[0]}
echo ${a[1]}
echo ${a[2]}
echo ${a[3]}
echo "數組元素依次如下:${a[@]}"
echo "數組元素依次如下:${a[*]}"

Full demo:

3) Get the length of the array

Add to the previous basis:

echo "數組元素個數爲:${#a[@]}"
echo "數組元素個數爲:${#a[*]}"

Right now

The demonstration is as follows:

Seven, shell operator

arithmetic operator

Demonstrating some of them, others are similar:

a=10
b=20

val=`expr $a + $b`
echo "a + b : $val"

val=`expr $a - $b`
echo "a - b : $val"

val=`expr $a \* $b`
echo "a * b : $val"

val=`expr $b / $a`
echo "b / a : $val"

val=`expr $b % $a`
echo "b % a : $val"

if [ $a == $b ]
then
   echo "a 等于 b"
fi
if [ $a != $b ]
then
   echo "a 不等于 b"
fi

The full demo is as follows:

Precautions:

  • There must be spaces between expressions and operators, for example, 2+2 is wrong and must be written as 2 + 2, which is different from most programming languages ​​we are familiar with.
  • The complete expression should be enclosed by two backticks. Note that this character is not a commonly used single quote, it is under the Esc key.
  • The multiplication sign (*) must be preceded by a backslash () to achieve multiplication;
  • if...then...fi is a conditional statement, which will be explained later.

I won’t talk about other operators, but mainly master arithmetic operators.

8. Shell echo command

You can test learning by entering such a one-line command directly in the terminal, without having to create new files all the time.

1) Display normal string

echo "hello world"

The double quotes here can be completely omitted, and the following commands have the same effect as the above example:

echo hello world

The full demo is as follows:

2) Show escape characters

echo "\"hello world\""

The demonstration is as follows:

3) Display newline

Use \n for newlines:

echo -e "hello\n"

The demonstration is as follows:

4) display does not wrap

echo -e "chuan! \c" # -e 开启转义 \c 不换行

Demo:

5) Display results redirected to file

Directed to the test7.sh file:

echo "hello world" >test7.sh

Demo:

6) Display execution time

echo `date`

Demo:

It’s the end here again, let’s add that printf has the same function as the echo command, so I won’t demonstrate it, and use echo to output uniformly.

9. Shell test command

1) Numerical test

The parameters and descriptions are as follows:

-eq 等于则为真
-ne 不等于则为真
-gt 大于则为真
-ge 大于等于则为真
-lt 小于则为真
-le 小于等于则为真

Demonstrate a parameter as follows:

num1=200
num2=200
if test $[num1] -eq $[num2]
then
    echo '两个数相等!'
else
    echo '两个数不相等!'
fi

Right now:

The full demo is as follows:

At this point, I first delete the file created earlier:

rm -rf test1.sh test2.sh test3.sh test4.sh test5.sh test6.sh test7.sh test8.sh

Demo:

The [] in the code perform basic arithmetic operations, for example:

a=10
b=10

result=$[a+b] # 注意等号两边不能有空格
echo "result結果为: $result"

The full demo is as follows (I created a new folder so as not to mess it up):

I only demonstrated addition, you can also try some other calculations.

2) String test

The parameters are as follows:

=   等于则为真
!=  不相等则为真
-z 字符串  字符串的长度为零则为真
-n 字符串  字符串的长度不为零则为真

Demo one is as follows:

num1="chuan"
num2="chuan"
if test $num1 = $num2
then
    echo '两个字符串相等!'
else
    echo '两个字符串不相等!'
fi

Right now:

The full demo is as follows:

3) File test

parameter:

-e 文件名  如果文件存在则为真
-r 文件名  如果文件存在且可读则为真
-w 文件名  如果文件存在且可写则为真
-x 文件名  如果文件存在且可执行则为真
-s 文件名  如果文件存在且至少有一个字符则为真
-d 文件名  如果文件存在且为目录则为真
-f 文件名  如果文件存在且为普通文件则为真
-c 文件名  如果文件存在且为字符型特殊文件则为真
-b 文件名  如果文件存在且为块特殊文件则为真

As an example:

if test -e ./test1.sh
then
    echo '文件已存在!'
else
    echo '文件不存在!'
fi

The full demo is as follows:

Other parameters can be tested by themselves.

Ten, shell control flow

1) if to judge flow

 The syntax of if else fi is as follows:

if condition
then
    command1 
    command2
    ...
    commandN 
fi

for example:

-gt 大于则为真

The test code is as follows:

a=5
b=6
if test [$a -gt]
then
        echo '大於'
else    
        echo '小於'
fi

The full demo is as follows:

Then the advanced test code is as follows:

a=5
b=6
if test [$a==$b]
then
        echo '等於'
elif [ $a -gt $b ]
then
   echo "a 大于 b"
elif [ $a -lt $b ]
then
   echo "a 小于 b"
else
   echo "没有符合的条件"
fi

The full demo is as follows:

2) for loop

grammar:

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

Written in one line it is:

for var in item1 item2 ... itemN; do command1; command2… done;

An example is as follows: sequentially output the numbers in the current list

for a in 1 2 3 4 5
do
    echo "值依次爲: $a"
done

The full demo is as follows:

Another example: sequentially output characters in a string

for str in hello chuan chuan
do
    echo $str
done

The full demo is as follows:

Let's go further: print the multiplication table of any number

echo "输入一个数:"
read num
for ((  i=1;i<=$num;i++  ))
do
   for ((  j=1;j<=$num;j++  ))
   do
      [  $j  -le  $i  ]  &&  echo -n "${i}*${j}=$((i*j))      "    #判断j是否小于i,当
j大于i时不输出,输出不换行,末尾加一个制表符
   done
   echo ""           #输出一个换行符                
done

The full demo is as follows:

3) while loop

Grammar format:

while condition
do
    command
done

For example: output 1 to 6 in sequence

int=1
while(( $int<=6 ))
do
    echo $int
    let "int++"
done

The full demo is as follows:

4) until loop

until Loop executes a sequence of commands until a condition is true and stops. The until loop is the exact opposite of the while loop. The syntax is:

until condition
do
    command
done

condition is generally a conditional expression, if the return value is false, continue to execute the statement in the loop body, otherwise jump out of the loop. For example: use the until command to output numbers from 0 to 6

a=0

until [ ! $a -lt 6 ]
do
   echo $a
   a=`expr $a + 1`
done

The full demo is as follows:

5)case ... esac

case ... esac is a multi-choice statement, similar to switch ... case in C language. Each case branch starts with a right parenthesis, and two semicolons;; indicate break, that is, the end of execution. The syntax is:

case 值 in
模式1)
    command1
    command2
    ...
    commandN
    ;;
模式2)
    command1
    command2
    ...
    commandN
    ;;
esac

Example: Prompt to enter 1 to 4 to match each pattern

echo '输入 1 到 4 之间的数字:'
echo '你输入的数字为:'
read a
case $a in
    1)  echo '你选择了 1'
    ;;
    2)  echo '你选择了 2'
    ;;
    3)  echo '你选择了 3'
    ;;
    4)  echo '你选择了 4'
    ;;
    *)  echo '你没有输入 1 到 4 之间的数字'
    ;;
esac

The full demo is as follows:

6) Break out of the loop

break  The break command allows to break out of all loops (terminate execution of all subsequent loops). The test code is as follows:

do
    echo -n "输入 1 到 5 之间的数字:"
    read aNum
    case $aNum in
        1|2|3|4|5) echo "你输入的数字为 $aNum!"
        ;;
        *) echo "你输入的数字不是 1 到 5 之间的! 游戏结束"
            b

The full demo is as follows:

continue  The continue command is similar to the break command, except that it does not break out of all loops, only the current loop. The test code is:

while :
do
    echo -n "输入 1 到 5 之间的数字: "
    read aNum
    case $aNum in
        1|2|3|4|5) echo "你输入的数字为 $aNum!"
        ;;
        *) echo "你输入的数字不是 1 到 5 之间的!"
            continue
            echo "游戏结束"
        ;;
    esac
done

The full demo is as follows:

Does anyone want to ask me how it ends? Just ctrl+c to force the end.

Eleven, Shell function

I won't talk about the fancy language, let's look at a demo function:

demoFun(){
    echo "測試一下我的函數!"
}
echo "函数开始执行"
demoFun
echo "-函数执行完毕"

If you have learned other languages, you must understand them at a glance. The full demo is as follows:

Here I will insert another example: read 10 numbers from the keyboard, and display the maximum and minimum values. The code is:

printf "请输入十个数字: "  
read   
biggest=$(echo "$REPLY" | tr ' ' '\n' | sort -rn | head -n1)  
smallest=$(echo "$REPLY" |  tr ' ' '\n' | sort -rn | tail -n1)  
echo "最大的数字为:  $biggest"  
echo "最小的数字为:  $smallest"

The full demo is as follows:

The following defines a function with a return statement: The code is:

add(){
    echo "这个函数为求两个函数之和.."
    echo "输入第一个数字: "
    read aNum
    echo "输入第二个数字: "
    read bNum
    echo "两个数字分别为 $aNum 和 $bNum !"
    return $(($aNum+$bNum))
}
add
echo "输入的两个数字之和为 $? !"

The full demo is as follows:

12. Shell input/output redirection

The relevant parameters are as follows:

command > file  将输出重定向到 file。
command < file  将输入重定向到 file。
command >> file 将输出以追加的方式重定向到 file。
n > file    将文件描述符为 n 的文件重定向到 file。
n >> file   将文件描述符为 n 的文件以追加的方式重定向到 file。
n >& m  将输出文件 m 和 n 合并。
n <& m  将输入文件 m 和 n 合并。
<< tag  将开始标记 tag 和结束标记 tag 之间的内容作为输入。

Do some examples:

1) Output redirection

redirect output to wen folder

Another example is that I redirect the file test16.sh to the file han

One disadvantage of such redirection is that it will overwrite the original content. If you don't want to overwrite the original content, you can use:

command >> file 将输出以追加的方式重定向到 file。

The full demo is as follows:

So we can see that it has been appended.

2) Input redirection

If you want to count how many lines are inside a folder:

wc -l wen

If we redirect the input to the wen file:

wc -l <  wen

Demonstrated as:

3)Here Document

Here Document is a special redirection method in Shell, which is used to redirect input to an interactive shell script or program. The syntax is;

command << delimiter
    document
delimiter

for example:

wc -l << EOF
   欢迎大家
   这里是川川菜鸟
   教程
EOF

Demo:

It can also be executed as a script:

cat << EOF
    欢迎大家
   这里是川川菜鸟
   教程
EOF

The demonstration is as follows:

4) /dev/null file

If you want to execute a command without displaying the output on the screen, you can redirect the output to /dev/null:

13. Practical exercises

1) Linux examples

If you don’t understand the following operations, please read this article of mine. After reading this article, you will understand: cat detailed tutorial input and output redirection: ① Create a new file file1, input :  Hello  , Linux ! Save and exit. Create a new file file2, enter: World! Save and exit. Display the contents of file1 and file2 on the terminal and redirect to file file3. Append the contents of file1 to file file3.

Operation steps: 1. Create a new folder work

mkdir work

2. Switch directory

cd work/

Full demo:

3. Create and edit a new file

touch file1

edit file

vim file1

View Files:

cat file

Full demo:

4. Create another file for the same reason, the complete demonstration is as follows:

5. Redirect to file3 file

cat file1 file2 >>file3

The full demo is as follows:

6. Append the contents of file1 to file file3

cat file1>>file3

The full demo is as follows:

②Pipeline: Count and display the number of lines in which "hello" appears in the file file3

grep Hello file3 |wc -l

The demonstration is as follows:

③Pipeline and input and output redirection: Enter the directory /home/student, use ls -l long format to list the files and directories under the current directory, and save the first 5 pieces of information to the file list. Create a new folder and edit list.txt as follows:

file1
file2
file3
file4
file5
file6
file7

Full demo:

Check it out:

View files and directories in the current directory

ls -al

Demo:

Filter the top 5 data and add it to file3:

ls -l |head -n 5 >>list.txt

The full demo is as follows:

2) Shell exercises

① Create 50 directories in the /home directory, and the directory names are: a1, ..., a50; Create a sh file:

touch 1.sh

The content is:

i=1

while [ $i -le 50 ]

do

mkdir a$i

i=$((i+1))

done

Full demo:

② Write a program, its function is: first check whether the name /root/test/logical exists. If it does not exist, create a file, use touch to create it, and leave after the creation is complete; if it exists, judge whether the name is a file, if it is a file, display its line number; if it is not a file, leave; Create 2.sh

touch 2.sh

The content is:

if [ ! -e /home/yifan/maying/shell/case5/logical ]  
then
    touch logical  
elif 
    [ -f /home/yifan/maying/shell/case5/logical ]  
then 
    rm -f /home/yifan/maying/shell/case5/logical && mkdir /home/yifan/maying/shell/case5/logical  
elif 
    [ -d /home/yifan/maying/shell/case5/logical ]  
then 
    rm -r /home/yifan/maying/shell/case5/logical  
fi

The demonstration is as follows:

Check it out:

③ Write a shell script, read 10 numbers from the keyboard, and display the maximum and minimum values

printf "请输入十个数字: "  
read   
biggest=$(echo "$REPLY" | tr ' ' '\n' | sort -rn | head -n1)  
smallest=$(echo "$REPLY" |  tr ' ' '\n' | sort -rn | tail -n1)  
echo "最大的数字为:  $biggest"  
echo "最小的数字为:  $smallest"

The full demo is as follows:

④ Write a script to print the multiplication table of any number. For example: input 3, then print 11=1 21=2 22=4 31=3 32=6 33=9 The code is as follows:

echo "输入一个数:"
read num
for ((  i=1;i<=$num;i++  ))
do
   for ((  j=1;j<=$num;j++  ))
   do
      [  $j  -le  $i  ]  &&  echo -n "${i}*${j}=$((i*j))      "    #判断j是否小于i,当
j大于i时不输出,输出不换行,末尾加一个制表符
   done
   echo ""           #输出一个换行符                
done

The full demo is as follows:

Guess you like

Origin blog.csdn.net/u010258235/article/details/131682103