Linux teaching items - basic environment and command teaching (including practical shell scripts)

Linux related learning - commands and others

Preliminary preparations (Linux system has been installed by default)

Demo system:

  1. Ubuntu stand-alone system
    Linux The-Land-Like-as-A-Picture 5.8.0-59-generic #66~20.04.1-Ubuntu SMP Thu Jun 17 11:14:10 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
  2. Virtual Machine Vmware 15
    CentOS 7

1. Network configuration:

stand-alone system

After the installation is complete, the configuration is complete

Virtual machine environment vmware:

Network Configuration

  1. right clicknetwork adapterSelect VMware Network 8, open
    VMnet8
  2. Choose to configure IPv4, the corresponding IP is192.168.1.1, the subnet mask is255.255.255.0
  3. Open vmware, modify the virtual network editor, corresponding to Vmnet8 as NAT mode (default) enable or disable DHCP service
    Vmware Virtual Network Editor
    Corresponding IP configuration
  4. Modify the corresponding settings of the virtual machine, the network adapter is NAT, and isconnectedstate
    Virtual machine device network settings
  5. Enter the system to modify the network:

Connect to the external network: set the virtual machinevirtual network adapterVM8DHCPOpen; the system network is set to DHCP to obtain automatically.
Do not connect to the external network: the system network is set to static, such as 192.168.1.200,That200Can be modified by yourself, the subnet mask is 255.255.255.0


2. Early software acquisition: take typora as an example

Prerequisite: The network can be connected to the external network

Official website link

Official website link

Installation Tutorial

wget -qO - https://typora.io/linux/public-key.asc | sudo apt-key add -
sudo add-apt-repository 'deb https://typora.io/linux ./'
sudo apt-get update
sudo apt-get install typora

3. Use of shortcut keys (Ubuntu)

Visual interface shortcut keys

  • Ctrl+ALT+T: Open a terminal (CentOS needs to open a terminal first)
  • Tab: Completion command
  • Ctrl+C: interrupt command

Linux initial common command learning

Partial reference: Linux common commands

1. What is an order

	命令名称 [选项] [参数] [对象]
	// 注意,命令名称、选项、参数和对象中间为空格

2. Directory commands of basic commands

pwd(print working directory)

pwd is used to display the current working directory of the user

cd(change directory)

cd is used to switch the working path, the format is "cd [directory name]"

.directory
_.Indicates in the current directory
..
directory..Indicates the previous directory of the current directory
cd and pwd

ls(list files )

ls is used to display the file information in the directory, the format is "ls [option] [file]"

	ls -al
	// 用于查看当前目录中所有文件并输出对应属性信息

mkdir(make directory )

mkdir is used to create folders, the format is "mkdir [name of the directory to be created]"

	mkdir -p test1/test2
	// mkdir -p 用于在文件夹中继续创建文件夹

rmdir(remove directory )

rmdir is used to delete folders (not commonly used)


3. File operation commands of commonly used commands

touch

touch is used to create files (multiple) such as:
touch file1 file2 。。。

mv(move file )

mv is used to move (usually rename) existing files or folders
as follows: rename the created file1 to file3:
mv file1 file3

rm(remove file )

rm (most commonly used), as a delete command, can be used to delete a file or folder

	rm file2
	// 此时并不会报错——原因:删除单个文件
	mkdir -p test\123\
	rm test\
	// 此时报错:删除的是目录
	rm -rf test
	// 删除成功

cp(copy file)

cp is used to copy files or folders. In linux, it is recommended to use cp as a backup of the original file when modifying files.
Common commands:
cp file2 [路径]/[文件名]

	cp -R test1 ../
	// 将之间新建的test1文件夹复制到上一级目录
	// 对文件夹的复制需要加 -p
	cp -a file3 ../
	// 将之前新建的file3文件复制到上一级目录
	// -a 用于不修改文件的属性,包括文件所有者,权限和创建时间等

ln (link files) soft link

ln -s file2 [路径]/[链接名]

cat (concatenate) view

less file advanced viewing command (recommended)

less [文件名]

related key usage

f: Turn page down
b: Turn page up
/: Search for characters
n: Continue to search for results down
q: Exit the file viewing interface

tar (tape archive) compression

	tar -xvf xxx.tar -C [路径]
	tar -zxvf xxx.tar.gz 
	tar -cvf xxx.tar [要压缩的文件]
	tar -czvf xxx.tar.gz [要压缩的文件]

4. Permission modification commands for commonly used commands

Linux permissions: rwx

  • r stands for readable read
  • w stands for writable write
  • X means that the file is an executable file.
    If any position of rwx becomes -, it means that it is not readable or writable or non-executable.

Permission Description:

  • The first digit: - means it is a file, d means it is a folder
  • The first paragraph (3 digits): represents the authority of the owner
  • The second paragraph (3 digits): represents the owner's group and the permissions of the group members
  • The third paragraph (the last 3 digits): represents the permissions of other users

chown(change owner )

chown is used to modify the owner of a file or folder, only files (folders)ownerandrootFile permissions can be modified

chgrp(change group )

chgrp is used to modify the group of a file or folder

chmod(change mode )

chmod is used to modify the corresponding permissions of files or folders

	mkdir sample	
	ls -l | grep sample
	chown jsj sample
	// 将root主目录下sample的拥有者改为jsj
	ls -l | grep sample
	chmod u-x,g-r,o+w sample
	// 将sample文件夹拥有者对应权限修改为没有执行权限x,组内成员没有可读权限r,其他用户拥有可写权限r
	ls -l | grep sample
	chmod 765 sample
	// 修改权限为 rwx rw- r-x (111 110 101)

Corresponding execution result


5. User login commands for common commands

su(swith user)

su is used to switch between users. However, the user before switching remains logged in. If root switches to a normal or virtual user, no password is required, otherwise a normal user needs password verification to switch to any other user.

	su test:切换到test用户,但是路径还是/root目录
	su - test : 切换到test用户,路径变成了/home/test

passwd

existroot userExecute the password modification for the corresponding user as follows
Usage:
passwd [对应用户]

who

who is used to view the user terminal information currently logged into the host, the format is "who [parameter]".

last

last is used to view the login records of all systems, the format is "last [parameter]"

history

history is used to display the 1000 commands executed by the current user history

	history -c
	// 清空当前用户执行linux命令历史信息记录

6. System work commands of commonly used commands

echo

echo is used to output strings or corresponding variables in the terminal (in the$headed by)

	echo -e "tab:\t回车:\n"
	// echo -e 为解析正则表达,如\t和\n等均可表达
	echo -n "echo -n 表示不回车输出"

Echo classic case: countdown:

	for i in 9 8 7 6 5 4 3 2 1 0
	do
		echo -ne "$i\b"
		# -n表示不回车显示,\b在正则表达为删除\b前一个字符
		# 显示效果即每次数字闪烁并消失,不回车
		sleep 1
		# 等待1s
	done
	echo "发射!"

date

date is used to display the current time

Display the current time by year-month-day hours:minutes:seconds

date "+%Y-%m-%d %H:%M:%S"

Set the time to April 5, 2030, 6:7:8

date -s "20300405 6:07:08"

Date classic case: use this time as the folder name

	getDate=`date +"%Y%m%d-%H.%M"`
	# 将当前时间以年月日-小时.分钟的形式获取并传入给变量getDate
	# 注意能实现的机制是 `` 的使用
	# 以下命令也可:
	GetDATE=$(date +"%Y-%m-%d %H.%M")
	mkdir $getDate
	mkdir $GetDATE
	# 创建对应的文件夹

reboot

Reboot is used to restart the
rebootsystem

shutdown

shutdown is used to specify the corresponding time to shut down or restart

	shutdown -h now
	// 立即关机
	shutdown -h 5
	// 5分钟后关机
	shutdown -r now
	// 立即重启

ps(process status)

ps is used to view the process status in the system, the format is "ps [parameter]"

View the processes currently running on the system

ps aux
ps -ef

top

top (equivalent to win's task manager) is used to dynamically monitor information such as process activity and system load, and refreshes every 10 seconds by default

pidof

pidof is used to query the PID value of a specified service process, the format is "pidof [parameter] [service name]"

kill

kill is used to terminate a service process with a specified PID, the format is "kill [parameter] [process PID]"

killall

killall is used to end all processes corresponding to a certain service in batches, such as closing the sshd service program (ie xshell service)

	pidof sshd
	killall sshd
	pidof sshd

7. Other commands of common commands

find find

	find . -name "*.log" -ls  
	// 在当前目录查找以.log结尾的文件,并显示详细信息。 
	find /root/ -perm 600   
	// 查找/root/目录下权限为600的文件 
	find . -type f -name "*.log"  
	// 查找当目录,以.log结尾的普通文件 
	find . -type d | sort   
	// 查找当前所有目录并排序 
	find . -size +100M  
	// 查找当前目录大于100M的文件

grep

	ps -ef | grep sshd  
	//查找指定ssh服务进程 
	ps -ef | grep sshd | grep -v grep 
	// 查找指定服务进程,排除gerp身 
	ps -ef | grep sshd -c 
	// 查找指定进程个数

cal(calendar )

cal [月份] [年份]
show calendar

dd(disk dump)

dd is used to create a file of a specified size

	dd if=/dev/zero of=file count=3 bs=100M
	# 在当前目录创建一个3*100M=300M大小的文件file
	ls -l file

man manual

man [对应有效指令]

vim (with reference)

Vim three states

Basically, vim can be divided into three states, which are command mode, insert mode and last line mode. The functions of each mode are as follows:

  • Command line mode command mode)
    to control the movement of the screen cursor, delete characters, words or lines, search, move and copy a certain section and enter Insert mode, or go to last line mode.
  • Common commands in command line mode:
  1. Control cursor movement: ↑, ↓, j
  2. delete current line: dd
  3. Find: / character
  4. Enter edit mode: ioa
  5. Enter bottom line mode:
  • Edit mode (Insert mode)
    Only in Insert mode can text input be performed, press the "ESC" key to return to the command line mode.
  • Commonly used commands in edit mode:
    ESC Exit edit mode to command line mode
  • The last line mode (last line mode)
    saves the file or exits vim, and can also set the editing environment, such as searching for strings, listing line numbers...etc.
  • Commonly used commands in bottom line mode:
  1. Quit editing: :q
  2. Force quit: :q!
  3. Save and exit: :wq

open a file

Command: vim file name
Example: open the aa.txt file vim aa.txt or vim aa.txt in the current directory

Note: After opening the file with the vim editor, it cannot be edited, because it is in command mode at this time, click the keyboard i/a/o to enter the edit mode.

edit file

Use the vim editor to open the file and click the button: i, a or o to enter the editing mode.

i: start inserting before the character where the cursor is (I: after)
a: start inserting after the character where the cursor is (A: before)
o: insert a new line below the line where the cursor is (O: above)

save or cancel editing

  • save document:
  1. ESC enters command line mode
  2. : enter bottom row mode
  3. wq save and quit editing
  • Cancel edit:
  1. ESC enters command line mode
  2. : enter bottom row mode
  3. q! Undo this modification and exit editing

Linux advanced shell script learning

1. What is a script (the abbreviation of shell script)

Shell script (shell script) is a script program written for the shell.

Shell editing available in linux

The corresponding location is /etc/shellsincluding sh, bash, etc. Bash, the Bourne Again Shell, is widely used in daily work due to its ease of use and free cost. At the same time, Bash is also the default shell for most Linux systems. to.shThe end of the file, bash xx.shsince the execution of the script.
/etc/shells

2. Write the corresponding script

For the writing of scripts, specifications are required, including

  1. The first line specifies which compiler to compile with
  2. The following describes the script creation time, corresponding author and corresponding purpose

xshell connection

Xshell creates a new connection, and the host fills in the virtual machine system IP, such as 192.168.1.200, with the username set toroot, and the password is the login password.

Reasons to use xshell

Under normal circumstances, the Linux system is a server, and most of the servers cannot contact the entity, that is, remote connection and control management can only be performed through the network. Among the common remote connection software, Xshell is the most commonly used. And Vim, as the built-in editor of Linux
, By omitting the use of the mouse, the editing process of the file content can be realized more quickly.

vim scripting

vim configuration file.vimrc

vim ~/.vimrc
Fill in the following:

set nu
# 设置行号,取消行号为 :set nonu
syntax on
# 设置自动修补
map <F1> :call AddInfo() <CR>
# 对于一个.sh文件,按F1键即可
function AddInfo()
        if &filetype == 'sh'
                call append(0,"#!/bin/bash")
        endif
        call append(1,"clear")
        call append(2,"#############################")
        call append(3,"###  Author: 此处为作者名称  ###")
        call append(4,"#############################")
        call append(5,"#time :".strftime("%Y-%m-%d %H:%M"))
        call append(6,"#############################")
        call append(7,"#### Descrption  ############")
        echo
endfunction

Esc :wqSave and exit

Create utility shell script files

Related resources: linux_shell.tar.gz
How to use: download or ftp to the linux system and decompress:
tar -zxvf linux_shell.tar.gz
it includes the script file corresponding to the blog, and the md tutorial, just use it according to the corresponding tutorial of the blog


test1.sh compares the size of two numbers

vim test1.shCreate the test1.sh script file,
first press the F1 key to write the script information:
current script content
ipressikey to enter input mode to start scripting:

clear
read -p "请输入两个数用于判断其大小,第一个数:" num1
read -p "第二个数:" num2
echo "第一个数是: $num1, 第二个数是:$num2"
echo "开始判断:"
if [ $num1 = $num2 ];then
        echo "$num1 等于 $num2"
        elif (($num1 > $num2));then
                echo "$num1 大于 $num2"
        else
                echo "$num1 小于 $num2" 
fi

according toZZSave the file and exit.
The final content is as follows:
test1.sh
Script execution:
bash test1.shEnter two numbers to judge:
Results of the


test2.sh calculates whether the input year is a profit year

vim test2.shCreate test2.sh script
PressF1To add information, pressikey to edit:

clear
read -p "请输入一个大于1000的四位数的年份: " year
count=`echo $year | awk '{print length($0)}'`
if [ $count -eq 4 ];then
        echo "year 是 $year"
        if (( $year % 100 != 0 ));then
                if (( $year %4 != 0 ));then
                        echo "$yaer 不是闰年"
                else
                        echo "$year 是闰年"
                fi
        elif (( $year % 400 != 0 ));then
                echo "$year 不是闰年"
        else
                echo "$year 是闰年"
        fi
else
        echo "输入位数不对"
fi

according toZZSave the file and exit.
The final content is as follows:
Judging leap year
Script execution:
bash test2.shEnter four digits to judge:
result


test3.sh small game - guess the number

vim test3.shCreate test3.sh script
PressF1To add information, pressikey to edit:

Random=$(($RANDOM % 100))
read -p "请输入一个100以内的整数:" num 
if [ $num -gt 100 -o $num -lt 1 ];then
        read -p "请输入从1到100内的整数:" num 
fi
count=1;
while [ $num -ne $Random ]
do
        count=$(($count+1))
        if [ $num -gt $Random ];then
                read -p "输入的 $num 大了,请输入小一点的:" num 
        else
                read -p "输入的 $num 小了,请输入大一点的:" num 
        fi
done
echo "游戏结束!所猜次数:$count ,最终结果:$Random = $num"

according toZZSave the file and exit.
The final content is as follows:
Judgment random number
Script execution:
bash test3.shEnter a number within 100 to start:
Results of the


test4.sh calculates how long the birthday is (a bit complicated)

vim test4.shCreate test4.sh script
PressF1To add information, pressikey to edit:

read -p "输入您的出生日期(yyyymmdd):" birthday
# 判断输入是否合法
birth=`echo $birthday | grep '[0-9]\{4\}[0-9]\{2\}[0-9]\{2\}'`
if [ "$birth" != "0" ];then
        echo "您的出生日期是:"
        date --date="$birthday" +"%Y年%m月%d日"
        TrueDay=`echo $?`
        if [ $TrueDay -ne 0 ];then
                echo "输入时间不正确"
                exit 1
        else
                year=`date --date="$birthday" +"%Y"`
                mouth=`date --date="$birthday" +"%m"`
                day=`date --date="$birthday" +"%d"`
                echo "您的生日是:$mouth$day日"
        fi
else
        echo "输入时间不正确或格式有误,正确格式为20210703"
        exit 1
fi
# 判断距离过生日还有多久
NowYear=`date +%Y`
NowBirth=$NowYear-$mouth-$day
NowBirthday=`date --date="$NowBirth" +%s`
Nowday=`date +%s`
if [ $NowBirthday -ge $Nowday ];then
        FromDay=$(($(($NowBirthday-$Nowday))/60/60/24))
        FromHour=$(($(($NowBirthday-$Nowday))/60/60%24))
        FromYear=$(($NowYear-$year))
        echo "还有$FromDay$FromHour时就可以过$FromYear岁生日"
        else
                NowB=$(($NowYear+1))-$mouth-$day
                NowBD=`date --date="$NowB" +%s`
                NextDay=$(($(($NowBD-$Nowday))/60/60/24))
                NextHour=$(($(($NowBD-$Nowday))/60/60%24))
                NextYear=$(($NowYear+1-$year))
                echo "还有$NextDay$NextHour时就可以过$NextYear岁生日"
fi

according toZZSave the file and exit.
The final content is as follows:
birthday judgment
Script execution:
bash test4.shEnter the corresponding format of yyyymmdd to judge:
Running Results - Judging Birthday


test5.sh input numbers and add up from 1

vim test5.shCreate test5.sh script
PressF1To add information, pressikey to edit:

clear
read -p "请输入一个正整数: " num 
if [ $num -gt 0 ];then
        sum=0
        for ((i=1;i<=$num;i++))
        do
                sum=$(($sum+$i))    
        done
        echo "其累加求和为$sum" 
else
        echo "$num 应该大于0"
fi

according toZZSave the file and exit.
The final content is as follows:
summation
Script execution:
bash test5.shEnter a positive integer to calculate:
sum result


test6.sh Basic operations such as judging the existence of files and folders

vim test6.shCreate test6.sh script
PressF1To add information, pressikey to edit:

read -p "请输入你想去的目录: 格式为 /xx/xx/ :" dir 
read -p "请输入你想创建的文件名: " filename
echo "即将在$dir中创建$filename文件"

mkdir -p $dir && cd $dir || cd $dir
pwd
# 文件不存在,则创建
if [ ! -e $filename ];then
        touch $filename
# 文件存在,则删除,并新建文件夹
elif [ -f $filename ];then
        rm -rf $filename
        mkdir $filename
# 存在,为文件夹等其他类型,则删除
else
        rm -rf $filename
fi
ls -l

according toZZSave the file and exit
The final content is as follows:
File and folder judgment
Script execution:
bash test6.shEnter the corresponding path and file name to create:
Result display


test7.sh Get information about surviving hosts in the current network segment

vim test7.shCreate test7.sh script
PressF1To add information, pressikey to edit:

read -p "请输入您的主机ip,如192.168.1.200:" ip
# 获取对应网段
getIP=`echo $ip | cut -d . -f 1,2,3`
endIp=255
startIp=0
while [ $startIp -ne $endIp ]
do
        FinalIp=$getIP.$startIp
        echo "ping $FinalIp"
        # ping ip,c 1次,i 1s,s 1024大小,t 255TTL
        ping -c 1 -i 1 -s 1024 -t 255 $FinalIp &> /dev/null
        result=`echo $?`
        if [ $result -eq 0 ];then
                echo "$FinalIp 存活" >> activePC.txt
        else
                echo "$FinalIp 对应PC关闭" >> closePC.txt
        fi
        startIp=$(($startIp+1))
done

according toZZSave the file and exit.
The final content is as follows:
ping corresponding IP

Script execution:
bash test7.shEnter the host IP to judge:
Corresponding to Ip communication situation
Obtain the IP of the PC that can communicate


test8.sh Add users and configure corresponding login passwords (root authority)

vim test8.shCreate test8.sh script
PressF1To add information, pressikey to edit:

# 必须在root用户下
echo "请确保在root用户下:"
quit=1
while [ $quit -ne 0 ] 
do
        read -p "输入您要添加的用户:" username
        useradd -d /home/$username -m $username -s /bin/bash
        read -p "输入 $username 的密码:" passwd
        echo "$username:$passwd" | chpasswd
        read -p "是否继续添加?继续请输入1,退出输入0:" quit
done

according toZZSave the file and exit.
The final content is as follows:
Add users in batches
Script execution:
bash test8.shenter the user and the corresponding password to add and switch:
Add user successfully


Guess you like

Origin blog.csdn.net/jack_zj123/article/details/118386838