Shell basic Commands

Source: Internet
Author: User
Tags aliases file copy stdin scp command secure copy egrep

Objective

We have successfully installed the Linux system--centos7, and now follow the super brother to the gate of Linux.

So!

Start a picture, equip all by dozen ...

What the hell is this black one?

Using Linux every day, is to open the virtual machine, sitting in front of the machine running Linux, the display is the output of the terminal, the keyboard for typing is the terminal input, this is a very straightforward explanation. Many times, the machine does not have a monitor and keyboard interface, but there is a TCP/IP network channel, we can use Xshell this software to run SSH software and machine communication

So, what is a terminal?

Terminal is the processing of computer host input a set of devices, in the TCP/IP era, any one computer can be used as another computer operating terminal
View terminal Information shell command

So how do I see what the current Linux endpoints are?

command, explain TTY    view current terminal who am I only show the current user is using the terminal and logon time W       View all terminals (full feature, display user name, terminal tag, login time, load and other information)
Configuration of the Linux command line

Linux System command Operation syntax format
Command Space Parameters Space What the file or path needs to process
Rm -rf /tmp/*
Ls -la /home
Get married -No car, no room. A woman's on the line.
Get married -A car with a room Mating

1. In general, "parameters" is optional, in some cases "file or path" is also optional

2. Parameters > The same command, with different parameters to perform different functions

Create a directory/oldboy

Under Windows:

Right-click > new Folder

Under Linux:

Make directory > mk dir > mkdir
-------------------------------Mkdir/oldboy
-------------------------------Cd/mkdir Oldboy
View Catalog/oldboy
Content under the #显示/oldboy Ls/oldboy
Change the current directory/location
CD/HOMECD ~CD-

What do you do if you change your way and get lost? Which directory am I in exactly?

Print the current working directory
Create a file or modify a file timestamp (file properties)
#触摸touch xxx.py
Edit File
#方法, command Vivim use VI to open oldboy.py, the default is command mode, you need to enter a/i into the edit mode, and then enter the text "Life is short,i using Python" press ESC, return to command mode input  : wq!  Force Save exit
W Write Write
Q quit
! Force or : x Save exit
------
: Q do not save exit
: q! Do not save forced exits
View File Contents
#猫, view files Cat xxx.py
#追加文字到文件
Cat >>/tmp/oldboy.txt << EOF
Moon Light in front of the bed
Floor shoes Two Pair
Eof
Linux shortcut keys
1.tab key    for auto-complete command/filename/directory Name

3.clear/cls Cleanup Terminal display
4.ctrl + C terminates the current operation
Show input to Terminal
#默认吧内容显示到终端上    echo "Super Brother 666"
#超哥平时比较低调, do not want to let others know him 666, how to do? or write "super Brother 666" to the file!
echo "Super Brother 666" >/tmp/chaoge.txt
Special symbols
REDIRECT Symbol
1.>> , append the text to the end of the file 2.> redirect symbol, empty the original file all content, and then overwrite the text to the end of the file
echo "oldboy-python666" >/tmp/oldboy.txt
echo "chaoge666" >>/tmp/oldboy.txt
------------------------------------
I want to write the result information of the command execution to the file
IP addr >/tmp/network.txt #标准输出重定向 put the command execution result information into the file
Copy (copy) command

Windows replication

Can be said to be quite simple CTRL + C copy Ctrl + V Sticker

Linux

Replication > Copy > CP
#移动xxx. PY to the/TMP directory CP xxx.py/tmp/
#移动xxx. Py by the way, renamed Chaoge.py
CP xxx.py/tmp/chaoge.py


Cp-r recursive, replicating directories and future generations of directories
Cp-p copy files while keeping file attributes intact
Cp-a equivalent to-PDR

CP is a good command, before you manipulate files, back up
CP main.py Main.py.bak
Move command

What the? Move command?

Mobile (move) command  > Move > Mvcd/home
#把老男孩从沙河这破地方, move to Chaoyang to Mv/home/shahe/oldboy/tmp/chaoyang
Delete command
Delete  > Remove > RMCD/TMPRM oldboy.py# default prompt to delete, need to enter Yrm-f oldboy.py #不需要提示, Force delete
#rm默认无法删除目录, you need to keep up with the parameter-R
rm-rf/tmp/oldboy/

--------
Friendly reminder: Beginners use RM command, snapshot virtual machine at any time
Xargs command
The Xargs command is a filter that passes parameters to other commands, specializes in converting standard input data into command-line arguments, and xargs can handle pipes or stdin and convert them into parameters for a particular command. Xargs default command is Echo, space is the default delimiter cat Oldboy.txta b c d E F gh i j k l m n# multi-line input single line output cat oldboy.txt|xargs#-n limit number of arguments to a single line

Cat Oldboy.txt|xargs-n3
Find command
#Linux里如何找到需要的文件 For example Oldboy.pyfind where (directory) what type (file type) is called name (filename) find/tmp/-type f  -name "oldboy.py"

Files ending #找出所有以. txt
find/tmp/-type f-name "*.txt"

#找出所有以. txt to the end of the file, and delete

sudo command

The sudo command is used to execute commands in other identities, and the default identity is root. The /etc/sudoers user who can execute the sudo instruction is set in. If an unauthorized user attempts to use sudo, a warning message is sent to the administrator. When using sudo, the user must first enter the password, then have a 5-minute expiration date, and the password must be re-entered after the deadline.

Grammar

sudo "Options" "Parameters"-B: Execute instructions in the background;-H: Display Help;-H: Set the home environment variable to the new identity of the home environment variable; k: the expiry of the password, that is, the next time you execute sudo will need to enter the password; -L: Lists the current user can execute and cannot execute the instruction;-P: Change the prompt symbol of the asking password;-s<shell>: Executes the specified shell;-u< user;: Takes the specified user as the new identity. If this parameter is not added, the default is root as the new identity;-V: Extended password expires 5 minutes;-V: Displays version information.

Instance

When is this sudo command used?

Look at the picture

What to do? Insufficient authority, this time need sudo ls/root to run as root, chaoge right small, root can always be!!

This is because the configuration sudo must edit the/etc/sudoers file, and only the root can be modified, we can edit the sudoers file directly through the Visudo command, using this command can also check the syntax, than directly edit vim/etc/sudoers more secure

Visudo edit sudoers File Write # allow root to run any commands anywhereroot    all= (All)       allchaoge  all= (All)       all   #允许chaoge在任何地方, execute any command
Switch Chaoge user at this time
# Thesu command is used to switch the current user identity to another user's identity, the change must enter the user account and password to change.
Su-chaoge
You can already use the sudo ls/root command
Pipeline command
The pipe symbol "|" provided by Linux Two commands are separated, and the output of the command to the left of the pipe character is entered as the command to the right of the pipe. Common usage:
#检查python程序是否启动ps-ef|grep "Python"
find/tmp/-type f-name "Oldboy.txt" |xargs ls-l

Command format: Command A | Command b

The Three Musketeers of Linux

Grep

(Global search Regular expression (RE) and print out of the line, full search of regular expressions and print out the lines) is a powerful text-search tool that can use regular expressions to search for text and print matching lines.

Grammar:
grep [parameter] [--color=auto] [string] filename
Detailed parameters:
-I: Ignore case
-N: Output line number
-V: Reverse Selection
--color = Auto: Add color to the keywords section

grep "What am I looking for"/tmp/oldboy.txt# excludes-V, excludes what I'm looking for grep-v "What am I looking for/tmp/oldboy.txt

Example, find the/etc/passwd root user, and line number, display color

cat/etc/passwd |grep ' root '--color=auto-n
head, tail command
Head displays the first few lines of the file, the first 10 rows by default
Tail shows the file after a few lines, the default after 10 lines
#查看前两行head-2/tmp/oldboy.txt# View the following two lines Tail-2/tmp/oldboy.txt
#显示文件10-30 rows
Head-30/tmp/oldboy.txt |tail-21

Sed

sed is a stream editor, which is a very useful tool in text processing and can be used perfectly in conjunction with regular expressions. When processing, the currently processed rows are stored in a temporary buffer called pattern space, followed by the SED command to process the contents of the buffer, and after processing is done, the contents of the buffer are sent to the screen. Then the next line is processed, so it repeats until the end of the file. The file content does not change unless you use redirection to store the output. SED is mainly used to automatically edit one or more files, to simplify the repeated operation of the file, to write the conversion program and so on.

Command format

sed [options] ' command ' file (s) sed [options]-F scriptfile file (s)

Options

-e<script> or--EXPRESSION=<SCRIPT>: processes the input text file with the specified script in the options;-f<script file > or--file=<script file : Process the input text file with the script file specified in the options,-H or--help: Display Help,-N or--quiet or--silent: Displays only the results of script processing;-V or--version: Displays version information.

SED command

A\ inserts text below the current line. I\ inserts text above the current line. C\ changes the selected line to a new text. d Delete, delete the selected row. D Delete the first line of the template block. s replaces the contents of the specified character H copy template block into an in-memory buffer. H appends the contents of the template block to the in-memory buffer. G Gets the contents of the memory buffer and overrides the text in the current template block. G gets the contents of the memory buffer and appends it to the text of the current template block. The list of characters cannot be printed. N reads the next input line, processing the new row with the next command instead of the first command. N appends the next input line to the template block and embeds a new line between them, changing the current line number. P Prints the line of the template block. P (uppercase) prints the first line of the template block. Q Exit sed. b lable branches to the markup in the script, branching to the end of the script if the branch does not exist. R file reads rows from file. The T-label if branch, starting from the last row, will cause the branch to be at the command with a label, or to the end of the script, once the condition satisfies or t,t the command. The T label Error branch, starting with the last line, will cause the branch to be at the command with a label, or at the end of the script, once an error or T,T command occurs. W file writes and appends the template block to the end of file.  W file writes and appends the first line of the template block to the end of file.  ! Indicates that the subsequent command has effect on all rows that are not selected.  = Prints the current line number.  # extend annotations before the next line break.  

SED replacement flag

G indicates a full-line replacement within the row.  p indicates that the line is printed.  W means writing the line to a file. X represents the interchange of text in the  template block and the text in the buffer.  y means translating one character to another (but not for regular expressions) \1 substring match tag & matched string marker

Sed meta Character set

^ Match line starts, such as:/^sed/matches all lines beginning with sed. The $ match line ends, such as:/sed$/matches all lines ending in sed. Any character that matches a non-line break, such as:/s.d/matches S followed by an arbitrary character, and finally D. * Match 0 or more characters, such as:/*sed/match all the templates are one or more spaces followed by the SED line. [] matches a specified range of characters, such as/[ss]ed/-match sed and sed.  [^] matches a character that is not within the specified range, such as:/[^a-rt-z]ed/matches the beginning of a letter that does not contain a-r and t-z, followed by the line of Ed. \(.. \) match substring, save matching characters, such as s/\ (love\) able/\1rs,loveable is replaced with lovers. & Save Search characters to replace other characters, such as S/love/**&**/,love this into **love**. \< matches the beginning of a word, such as:/\<love/matches a line containing a word that begins with love. \> matches the end of a word, such as/love\>/matches a line containing a word ending in love. X\{m\} repeats characters x,m times, such as:/0\{5\}/matches a row containing 5 0. X\{m,\} repeats the character x, at least m times, such as:/0\{5,\}/matches at least 5 rows of 0. X\{m,n\} repeats the character x, at least m times, not more than n times, such as:/0\{5,10\}/matches 5~10 0 rows.
sed actual use Cases
All Oldboy in #替换oldboy. txt become oldboy_python# When the result is output to the screen and will not be written to the file sed ' s/oldboy/oldboy_python/'/tmp/oldboy.txt
#使用选项-I, match each line with the first Oldboy replaced by Oldboy_python and write to the file
Sed-i ' s/oldboy/oldboy_python/'/tmp/oldboy.txt
#使用替换标记g, you can also replace all matches
Sed-i ' s/book/books/g '/tmp/oldboy.txt
#删除文件第二行
Sed-i ' 2d '/tmp/oldboy.txt
#删除空白行
Sed-i '/^$/d '/tmop/oldboy.txt
#删除文件第二行, all rows to the end
Sed ' 2, $d '/tmp/oldboy.txt
#显示10-30 rows
-P--print
-N--cancels the default output
Sed-n ' 10,30p '/tmp/oldboy.txt

Akw

awk is a programming language that is used to process text and data under Linux/unix. The data can come from standard input (stdin), one or more files, or the output of other commands. It supports advanced functions such as user-defined functions and dynamic regular expressions, and is a powerful programming tool under Linux/unix. It is used in the command line, but more is used as a script. Awk has many built-in features, such as arrays, functions, and so on, which are the same as the C language, and flexibility is the biggest advantage of awk.

Grammar:

awk [option] ' script ' var = value Filenameawk [options]-F scriptfile var=value filename

Common Command options:

-F FS   FS specifies an input delimiter, FS can be a string or regular expression, such as-f:-v Var=value   assign a user-defined variable, pass an external variable to awk-f scripfile  read the awk command from the script file-m[fr ] Val   sets an intrinsic limit on the Val value, the-MF option limits the maximum number of blocks allocated to Val; the-MR option limits the maximum number of records. These two features are the extended functionality of the Bell Lab version of AWK and are not available in standard awk.
Instance
#NR  > Line number awk ' nr==20,nr==30 '/tmp/oldboy.txt
which command
The which command is used to find and display the absolute path of a given command, and the environment variable path holds the directory that needs to be traversed when the find command is saved.
The which directive looks for eligible files in the directory where the environment variable $path is set.
That is, with the which command, you can see whether a system command exists, and the command that executes exactly which location.
which PWD
which Python
Aliases alias command

Linux in the use of RM (delete), CP (overlay), MV (moving) and other commands, must be very careful, because these commands are "bombs", presumably everyone has heard "delete the library to run", a word "RM-RF/", if you really do so, then ... God bless you

How does Linux prompt you to be careful when using these commands? #查看系统别名alias
Default aliases

Alias cp= ' Cp-i '
Alias egrep= ' Egrep--color=auto '
Alias fgrep= ' Fgrep--color=auto '
Alias grep= ' grep--color=auto '
Alias l.= ' ls-d. *--color=auto '
Alias ll= ' Ls-l--color=auto '
Alias ls= ' ls--color=auto '
Alias mv= ' Mv-i '
Alias rm= ' Rm-i '
Alias Which= ' Alias | /usr/bin/which--tty-only--read-alias--show-dot--show-tilde '

The alias function is:

Our use of CP in Linux is equivalent to performing a cp-i
-I: Ask the user before deleting an existing file or directory;

#别名用比较危险的操作 to prevent you from making mistakes

Set an alias for RM
#让系统显示 do not use Rmecho does not use rm# set RM alias alias Rm= ' echo do not use RM '
#设置别名永久生效, write to/etc/profile (set environment variables for the signed-in user's contract)
Vim/etc/profile #编辑文件
G quickly reach the last line
o The next line of the current row, create a new row, enter edit mode
Source/etc/profile #读取文件 (contract effective)
---------------
#取消别名
Unalias RM
SEQ Command
The SEQ command is used to generate all integers from one number to another.

Grammar

seq [Options] ... Mantissa seq [Options] ... First number mantissa seq [Options] ... First number increment Mantissa

Parameters

-F, the--format= format        uses the printf-style floating-point format-S, the--separator= string   separates numbers using the specified string (by default: \ n)-W,--equal-width        adds 0 before the column to make the same width

Example

#显示1-50 integers
SEQ 50
#以000方式显示9-11 interval integer seq- F "%03g" 9 11
#以000方式显示1-100 interval integers
Seq-f "%03g" 1 100
which command

The Linux which command is used to locate files.

The which directive looks for eligible files in the directory where the environment variable $path is set.

Syntax which "parameter" "file" parameter:-n< filename length > Specifies the length of the file name, the length specified must be greater than or equal to the longest file name in all files. The-p< filename length > is the same as the-n parameter, but here the < filename length > includes the path to the file. -W Specifies the width of the field at the output. -V Displays version information.

Instance

Which Python       #python命令在哪/usr/bin/python    #命令文件绝对路径
SCP command

Linux SCP commands are used to copy files and directories between Linux.

SCP is the abbreviation for secure copy, and SCP is a secure remote file Copy command under the Linux system based on SSH login.

Syntax SCP "Optional Parameters" local source file Remote file tag

Parameters

-r: Recursively copy entire Directory-V: Verbose output-Q: Do not show transfer progress bar-C: Allow compression

Instance

#传输本地文件到远程地址scp local file  remote user name @ Remote IP: Remote folder/SCP local file  remote user name @ Remote IP: Remote folder/remote file name scp/tmp/chaoge.py [email protected]:/ home/scp/tmp/chaoge.py [email protected]:/home/chaoge_python.pyscp-r  Local folder  remote user name @ Remote IP: Remote folder/scp-r/tmp/ Oldboy [Email protected]:/home/oldboy# copy remote file to local SCP [email protected]:/home/oldboy.txt/tmp/oldboy.txtscp-r [email] protected]:/home/oldboy/home/
Du command

The Linux du command is used to display the size of a directory or file.

DU displays the disk space occupied by the specified directory or file.

Usage du "parameters" "File or directory"
-S Display totals
-h is displayed in K,m,g and is highly readable

Instance

Show directory or file occupied space # Nothing to do with, represents the current directory all file sizes du #显示/home   Total size du-sh/home
Top command

The Linux top command is used to display the dynamics of the process in real time

Let's analyze a piece of information.

Statistical information Area

First line (uptime) system time master run time user connections (WHO) system 1,5,15 minute average load second row: Process information process total number of processes running process number of processes that have been stopped process count zombie process number Third line: CPU information 1.5 US: Percentage of CPU occupied by user space 0.9 sy: CPU percentage of kernel space 0.0 ni: Percentage of CPU that has changed priority in user process space 97.5 ID: Percentage of idle CPU 0.2 wa: Percentage of CPU time waiting for input and output 0.0 Hi: Hardware CPU interrupt consumption percentage 0.0 si: Soft interrupt occupancy percentage 0.0 ST: Virtual machine occupancy percentage

Line four: Memory information (similar to the information on line fifth and the free command)

    • 8053444 Total: Amount of physical memory
    • 7779224 used: Total amount of memory used
    • 274220 Free: Total idle memory (free+used=total)
    • 359212 buffers: Memory used as the kernel cache
Line five: Swap information 8265724 total: Swap partition totals 33840 used: Total number of swap partitions used 8231884 free: Total idle swap area 4358088 cached Mem: Buffer swap total, contents in memory swapped out to swap area, It is then swapped into memory, but the used swap area is not overwritten, the swap area is already in the size of the swap area in memory, and the corresponding memory is swapped out again without having to write to the swap area.
Children's shoes often meet the question:
Question 1:
yudanl:~ yuchao$ cd~-bash:cd~: Command not found

Question 2:
yudanl:~ yuchao$ CD/OLDBOY-BASH:CD:/oldboy:no such file or directory

Little Practice
1. How do I enter the/home/oldboy directory before entering the/home/python directory? 2. How do I execute a/home/my_first.py file in the/home.python directory? 3. Ask each other questions relative paths and absolute paths
4. Write "Lift is short,i use Python" to the my_first.py file
5. Create a/TMP/OLDBOY/PYTHON/S11 with one command
6. View only 20 to 30 lines of content in the Oldboy_python.txt file (50 rows)

TIP:

Http://linux.51yip.com/http://man.linuxde.net/Linux Command Query Manual
Linux terminal under ESC +. Can get last file name

Shell basic Commands

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.