目录

0. 前言

1. 文件及目录管理

1.1 pwd:现在在哪儿

1.2 cd: 去往目标路径

1.3 ls: 指定目录下都有啥

1.3.1 查找占用空间最大的文件

1.4 tree: 列出目录树结构

2. 文件及目录操作

2.1 删除命令:rm

2.2 复制命令:cp

2.3 移动或改名:mv

2.4 显示文件内容:cat, more, less, head, tail

2.4.1 head command

2.4.2 tail command

2.4.3 cat

2.4.4 more

2.4.5 less

2.5 创建目录:mkdir

2.6 删除目录:rmdir

2.7 创建空文件:touch

3. 压缩和解压缩

3.1 tar

3.2 zip文件[解]压缩

3.3 bz2文件[解]压缩

3.4 7z文件[解]压缩 

3.5 Xz文件[解]压缩 

4. 搜索、替换和比较

4.1 搜索某个文件:which, whereis, locate, find

4.1.1 locate command

4.1.2 find command

4.1.3 grep command

4.1.4 sed:指定目录中全局字符串替换

4.1.5 which

4.1.6 whereis :查找

4.2 diff command

5. 系统管理

5.1 sudo

5.2 权限设置:chmod, chown

5.2.1 chmod:访问权限设置

5.2.2 chown:设置文件或目录的主人

5.2.3 chgrp:设计文件或者目录属于哪个组

5.2.4 查询组成员

5.2.5 查询某用户属于哪个(哪些)组 

5.3 磁盘空间状况查询:df, du

5.3.1 df

5.3.2 du (Disk Usage)

5.4 进程状态查询管理:ps, top, kill, job

5.4.1 ps

5.4.2 top

5.4.3 kill command

5.4.5  jobs command

5.5 内存管理:free

5.6 用户加入和删除:useradd, userdel

5.7 修改密码、查看当前用户、查看当前在线用户

5.8 su: 切换用户

5.9 sudo: 切换用户 

5.10 查询系统版本信息

5.11 安装软件

6. 其它

6.1 创建链接:ln

6.2 日期与时间

6.3 ping command

6.4 wget command

6.5 uname command

6.6 history command

6.6.1 history命令显示日期和时间

6.6.2 调整history记录的条数

6.7 man command

6.8 echo command

6.9 hostname command

6.10 用&&进行多个命令的串行连接

6.11 快速清空文件

7. Shell

 7.1 linux shell快捷键 

7.2 如何快速查看Linux系统上的Shell类型


0. 前言

        简要介绍Linux最常见常用的一些命令。方便实际需要使用时速查。一般linux命令都有非常多的选项。这里也只介绍常用的一些选项。一些不常用的高冷选项可以直接通过比如说cmd --help或者man cmd等进行查询。

        首先介绍一些linux命令行窗口使用时的一个小贴士和小技巧(Some tips and tricks):

        Use the clear command to clean out the terminal if it is getting cluttered with too many past commands.

        Try the TAB button to autofill what you are typing. For example, if you need to type Documents, begin to type a command (let’s go with cd Docu, then hit the TAB key) and the terminal will fill in the rest, showing you cd Documents.

        Ctrl+C and Ctrl+Z are used to stop any command that is currently working. Ctrl+C will stop and terminate the command, while Ctrl+Z will simply pause the command.

        If you accidental freeze your terminal by using Ctrl+S, simply undo this with the unfreeze Ctrl+Q.

        Ctrl+A moves you to the beginning of the line while Ctrl+E moves you to the end.

        You can run multiple commands in one single command by using the “;” to separate them. For example Command1; Command2; Command3. Or use && if you only want the next command to run when the first one is successful.

1. 文件及目录管理

1.1 pwd:现在在哪儿

        pwd 查看当前路径

        不同shell可能有不同版本的pwd命令,比如说支持更多一些的功能选项。可以用pwd --help或者man pwd等查询当前环境下的pwd命令支持哪些选项。

1.2 cd: 去往目标路径

        cd是change directory的缩写。基本用法:

cd toPath # 到指定目录,toPath可以是相对路径,也可以是完整的绝对路径

cd ..         # (with two dots) to move one directory up

cd            # 不带参数,回到用户自己的home directory

cd -          # (with a hyphen) to move to your previous directory

        需要注意的一点是,Linux’s shell is case sensitive(区分大小写的). So, you have to type the name’s directory exactly as it is. 

1.3 ls: 指定目录下都有啥

        基本用法:

ls        # 简要当前目录下列出各文件和子文件夹名

ls -al   # 列出各文件和子文件夹详细信息, such as the permissions, size, owner, etc.      

ls -R   # list all the files in the sub-directories as well

ls -a    #show the hidden files

        以上使用方法中没有指定目录路径,所以缺省地是显示当前目录下的内容。如果要显示(非当前目录的)指定目录下的内容,可以在命令行另行指定目录路径信息,如下所示:

ls -al  PathToFolder     # 简要当前目录下列出各文件和子文件夹名

1.3.1 查找占用空间最大的文件

ls -lSrh

1.4 tree: 列出目录树结构

 1 tree命令行参数:
 2    不带参数,显示所有正常文件和目录 
 3 -a 显示所有文件和目录,以及隐藏文件(比如说以“.”开头的文件)
 4 -A 使用ASNI绘图字符显示树状图而非以ASCII字符组合。
 5 -C 在文件和目录清单加上色彩,便于区分各种类型。
 6 -d 显示目录名称而非内容。
 7 -D 列出文件或目录的更改时间。
 8 -f 在每个文件或目录之前,显示完整的相对路径名称。
 9 -F 在执行文件,目录,Socket,符号连接,管道名称名称,各自加上"*","/","=","@","|"号。
10 -g 列出文件或目录的所属群组名称,没有对应的名称时,则显示群组识别码。
11 -i 不以阶梯状列出文件或目录名称。
12 -I 不显示符合范本样式的文件或目录名称。
13 -l 如遇到性质为符号连接的目录,直接列出该连接所指向的原始目录。
14 -L n  #n代表数字..表示要显示几层...
15 -n 不在文件和目录清单加上色彩。
16 -N 直接列出文件和目录名称,包括控制字符。
17 -p 列出权限标示。
18 -P 只显示符合范本样式的文件或目录名称。
19 -q 用"?"号取代控制字符,列出文件和目录名称。
20 -s 列出文件或目录大小。
21 -t 用文件和目录的更改时间排序。
22 -u 列出文件或目录的拥有者名称,没有对应的名称时,则显示用户识别码。
23 -x 将范围局限在现行的文件系统中,若指定目录下的某些子目录,其存放于另一个文件系统上,则将该子目录予以排除在寻找范围外。

        以下为一个tree命令执行结果示例:

        但是,在一些linux发行版中并没有默认安装tree。需要用户自行安装。在RedHat发行版中可以用yum命令进行安装(linux下安装软件需要系统管理员权限):

yum install tree

安装结果如下:

2. 文件及目录操作

2.1 删除命令:rm

The rm command is used to delete directories and the contents within them. If you only want to delete the directory — as an alternative to rmdir — use rm -r.

Note: Be very careful with this command and double-check which directory you are in. This will delete everything and there is no undo.

2.2 复制命令:cp

Use the cp command to copy files from the current directory to a different directory. For instance, the command cp scenery.jpg /home/username/Pictures would create a copy of scenery.jpg (from your current directory) into the Pictures directory.

2.3 移动或改名:mv

The primary use of the mv command is to move files, although it can also be used to rename files.

The arguments in mv are similar to the cp command. You need to type mv, the file’s name, and the destination’s directory. For example: mv file.txt /home/username/Documents.

To rename files, the Linux command is mv oldname.ext newname.ext

2.4 显示文件内容:cat, more, less, head, tail

2.4.1 head command

The head command is used to view the first lines of any text file. By default, it will show the first ten lines, but you can change this number to your liking. For example, if you only want to show the first five lines, type head -n 5 filename.ext.

2.4.2 tail command

This one has a similar function to the head command, but instead of showing the first lines, the tail command will display the last ten lines of a text file. For example, tail -n filename.ext.

2.4.3 cat

        cat后跟要显示的文本文件名即可:

$ cat Makefile   

2.4.4 more

         more后跟要显示的文本文件名即可:

$ more Makefile   

2.4.5 less

         less后跟要显示的文本文件名即可:

$ less Makefile   

        cat,more,less三者的区别?

2.5 创建目录:mkdir

Use mkdir command to make a new directory — if you type mkdir Music it will create a directory called Music.

There are extra mkdir commands as well:

  • To generate a new directory inside another directory, use this Linux basic command mkdir Music/Newfile
  • use the (parents) option to create a directory in between two existing directories. For example, mkdir -p Music/2020/Newfile will create the new “2020” file.

2.6 删除目录:rmdir

If you need to delete a directory, use the rmdir command. However, rmdir only allows you to delete empty directories.

2.7 创建空文件:touch

The touch command allows you to create a blank new file through the Linux command line. As an example, enter touch /home/username/Documents/Web.html to create an HTML file entitled Web under the Documents directory.

3. 压缩和解压缩

3.1 tar

The tar command is the most used command to archive multiple files into a tarball — a common Linux file format that is similar to zip format, with compression being optional.

This command is quite complex with a long list of functions such as adding new files into an existing archive, listing the content of an archive, extracting the content from an archive, and many more. Check out some practical examples to know more about other functions.

        file.tar.gz或file.tgz文件解压缩:

tar -xzvf file.tar.gz  #    解压并生成在当前目录下

        生成archive and compress   

tar -czvf filename.tar.gz srcfolder|srcfile

3.2 zip文件[解]压缩

Use the zip command to compress your files into a zip archive, and use the unzip command to extract the zipped files from a zip archive.

        Linux中解压缩*.zip文件:unzip filename.zip   

        Linux中压缩*.zip文件:

3.3 bz2文件[解]压缩

        file.bz2文件解压缩方法:

tar -jxvf   file.bz2     

3.4 7z文件[解]压缩 

7za x  file.7z  # 解压缩,redhat

7za a file.7z folderpath  # 压缩,redhat

        不同版本的linux系统下命令可能会略有不同。 

3.5 Xz文件[解]压缩 

How to Extract (Unzip) tar.xz File | Linuxize

Xz is a popular algorithm for compressing files based on the LZMA algorithm. By convention, the name of a tar archive compressed with xz ends with either .tar.xz or .txz

【解压整个文件包】

tar -xf archive.tar.xz

tar -xvf archive.tar.xz

tar -xf archive.tar.xz -C extract-to-path

tar -xf archive.tar.xz --directory extract-to-path

        选项“v”表示verbose,即解压过程中会打印出详细的解压信息。 

        选项“f”表示指定待处理文件

        在Windows下也可以用7zip工具进行解压。

【解压某个或某些文件或文件夹】

tar -xf archive.tar.xz path-to-file1 path-to-file2 

tar -xf archive.tar.xz dir1 dir2

tar -xf archive.tar.xz --wildcards '*.png'

【列出压缩包内容】

        使用这个命令,需要指定待解压文件的精确的文件名(含路径)。当待解压包非常大,而只需要从中提取少量文件时可以用这种方法解压。如果要知道压缩包中有什么文件时,可以用"--list"或者“-t”选项。甚至还可以用通配符来指定提取某些有共同特征的文件。

【创建压缩文件】

tar -cf archive.tar foo bar  # Create archive.tar from files foo and bar.

tar -cf archive.tar dir  # Create archive.tar from the specified directory.

4. 搜索、替换和比较

4.1 搜索某个文件:which, whereis, locate, find

4.1.1 locate command

You can use this command to locate a file, just like the search command in Windows. What’s more, using the -i argument along with this command will make it case-insensitive, so you can search for a file even if you don’t remember its exact name.

To search for a file that contains two or more words, use an asterisk (*). For example, locate -i school*note command will search for any file that contains the word “school” and “note”, whether it is uppercase or lowercase.

4.1.2 find command

Similar to the locate command, using find also searches for files and directories. The difference is, you use the find command to locate files within a given directory.

As an example, find /home/ -name notes.txt command will search for a file called notes.txt within the home directory and its subdirectories.

Other variations when using the find are:

  • To find files in the current directory use, find . -name notes.txt
  • To look for directories use, / -type d -name notes. txt

4.1.3 grep command

Another basic Linux command that is undoubtedly helpful for everyday use is grep. It lets you search through all the text in a given file.

To illustrate, grep blue notepad.txt will search for the word blue in the notepad file. Lines that contain the searched word will be displayed fully.

4.1.4 sed:指定目录中全局字符串替换

sed -i “s/oldstring/newstring/g” `grep oldstring -rl path` 

        -i 表示inplace edit,就地修改文件(所以初学者使用最好先做好备份!)
        -r 表示递归式地搜索子目录
        -l 表示输出匹配的文件名

        oldstring:原字符串

        newstring:要替换称为的字符串

        path:路径,可以是一个文件路径,也可以是一个目录路径

        注意:grep命令前后是一对“`”,不是单引号,是键盘左上角的那个!

4.1.5 which

4.1.6 whereis :查找

        该指令会在特定目录中查找符合条件的文件。该指令只能用于查找二进制文件、源代码文件和man手册页,一般文件的定位需使用locate命令。比如:

whereis csh  #当前系统用的是cshell, 这条命令查找csh在哪儿

4.2 diff command

Short for difference, the diff command compares the contents of two files line by line. After analyzing the files, it will output the lines that do not match. Programmers often use this command when they need to make program alterations instead of rewriting the entire source code.

The simplest form of this command is diff file1.ext file2.ext

5. 系统管理

5.1 sudo

Short for “SuperUser Do”, this command enables you to perform tasks that require administrative or root permissions. However, it is not advisable to use this command for daily use because it might be easy for an error to occur if you did something wrong.

5.2 权限设置:chmod, chown

5.2.1 chmod:访问权限设置

        chmod is another Linux command, used to change the read, write, and execute permissions of files and directories. As this command is rather complicated, you can read the full tutorial in order to execute it properly.

        加上“-R”可以递归地改变一个目录底下所有文件或目录对象的访问权限:

        Example:  chmod -R 777 /Path/To/Folder

5.2.2 chown:设置文件或目录的主人

        In Linux, all files are owned by a specific user. The chown command enables you to change or transfer the ownership of a file to the specified username. For instance, chown linuxuser2 file.ext will make linuxuser2 as the owner of the file.ext.

        同样可以使用“-R”选项进行递归式的设置。

5.2.3 chgrp:设计文件或者目录属于哪个组

        chgrp groupname file/folder

        同样可以使用“-R”选项进行递归式的设置。

5.2.4 查询组成员

        getent group groupname

5.2.5 查询某用户属于哪个(哪些)组 

        groups username

5.3 磁盘空间状况查询:df, du

5.3.1 df

Use df command to get a report on the system’s disk space usage, shown in percentage and KBs. If you want to see the report in megabytes, type df -m.

5.3.2 du (Disk Usage)

        常见用法:

du -h --max-depth=k

du -h -d k

-h是指生成human-readable格式的输出

"-d k" 或者“--max-depth=k”是指生成几级深度的信息,0表示仅生成当前目录的总的空间大小,1表示同时回到第1级子目录的信息,以下依此类推。。。当然如果不用该参数的话会缺省把所有层次信息都给出来,这样反而会很难看。

注意:是max-depth而不是max_depth!

5.4 进程状态查询管理:ps, top, kill, job

5.4.1 ps

最常用的使用方式,列出用户自己的进程:

ps -aux 

        注意以上所显示的PID号。kill命令即是基于PID来进行进程消杀。

        再加上管道连接grep命令即可查看指定用户运行的进程

ps aux | grep -v `whoami`

5.4.2 top

As a terminal equivalent to Task Manager in Windows, the top command will display a list of running processes and how much CPU each process uses. It’s very useful to monitor system resource usage, especially knowing which process needs to be terminated because it consumes too many resources.

5.4.3 kill command

结合ps命令使用,参见上面ps命令的说明。

If you have an unresponsive program, you can terminate it manually by using the kill command. It will send a certain signal to the misbehaving app and instructs the app to terminate itself.

There is a total of sixty-four signals that you can use, but people usually only use two signals:

  • SIGTERM (15) — requests a program to stop running and gives it some time to save all of its progress. If you don’t specify the signal when entering the kill command, this signal will be used.
  • SIGKILL (9) — forces programs to stop immediately. Unsaved progress will be lost.

Besides knowing the signals, you also need to know the process identification number (PID) of the program you want to kill. If you don’t know the PID, simply run the command ps ux.

After knowing what signal you want to use and the PID of the program, enter the following syntax:

kill [signal option] PID

5.4.5  jobs command

jobs command will display all current jobs along with their statuses. A job is basically a process that is started by the shell.

5.5 内存管理:free

5.6 用户加入和删除:useradd, userdel

Since Linux is a multi-user system, this means more than one person can interact with the same system at the same time. useradd is used to create a new user, while passwd is adding a password to that user’s account. To add a new person named John type, useradd John and then to add his password type, passwd 123456789.

To remove a user is very similar to adding a new user. To delete the users account type, userdel UserName

5.7 修改密码、查看当前用户、查看当前在线用户

#passwd 修改密码,再次确认,区分大小写

#whoami 就是一条查看自己用户名的命令

#users/who/w 就是查看当前在线用户

5.8 su: 切换用户

su username  # 切换到指定用户名,当然会要求输入密码

su                   # 不带参数的话,表示要求切换为root user

        如果你只需要临时以其它用户名执行一条命令的话,可以不用切换过去,而是以以下方式执行,'command'表示要执行的命令:  

su -c command username 

        例如:

su -c chmod +w /Downloads testuser

        su当然还有其它种种选项,这里不再赘述。 

5.9 sudo: 切换用户 

        sudo与su的作用大同小异,差异在于选项的不同,以下为一些典型的使用方法:

sudo -u username

sudo -u username command

sudo -u testuser chmod 777 /Documents

sudo        

5.10 查询系统版本信息

uname -a

        输出信息如以下例所示:

Linux server8 3.10.0-1160.76.1.el7.x86_64 #1 SMP Wed Aug 10 16:21:17 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

 lsb_release -a

        输出信息如以下例所示:

LSB Version:    :core-4.1-amd64:core-4.1-ia32:core-4.1-noarch
Distributor ID:    n/a
Description:    NAME="Red Hat Enterprise Linux Server"
Release:    n/a
Codename:    n/a 

5.11 安装软件

        安装软件需要系统管理员权限。在linux不同发行版中软件安装命令也不同。

        redhat中用的是yum命令。安装使用示例参见上面1.4节 

6. 其它

6.1 创建链接:ln

        参见:Linux Tips: How to Create Link in Linux? 

6.2 日期与时间

6.3 ping command

Use the ping command to check your connectivity status to a server. For example, by simply entering ping google, the command will check whether you’re able to connect to Google and also measure the response time.

6.4 wget command

The Linux command line is super useful — you can even download files from the internet with the help of the wget command. To do so, simply type wget followed by the download link.

6.5 uname command

The uname command, short for Unix Name, will print detailed information about your Linux system like the machine name, operating system, kernel, and so on.

6.6 history command

When you’ve been using Linux for a certain period of time, you’ll quickly notice that you can run hundreds of commands every day. As such, running history command is particularly useful if you want to review the commands you’ve entered before.

6.6.1 history命令显示日期和时间

        history的作用就是将bash执行过的所有命令存储到.bash_history文件中,帮助复查用户命令。默认情况使用history确实是不会输出命令执行的时间和日期,尽管这个命令记录得到时间。运行history命令的时候,会检查一个HISTIMEFORMAT的环境变量,这个变量制定了怎么去格式化输出这个命令中存储的时间,如果这个值为null,那就是默认不显示。现在使用strftime格式化时间,有三种方式:

(1)临时设置HISTIMEFORMAT变量,在下次机器重启前生效

# export HISTIMEFROMAT=‘%F %T’

(2)将变量添加到.bashrc或者.bash_profile文件中,永久生效

# echo echo'HISTTIMEFORMAT="%F %T "'>>~/.bashrc 或者~/.bash_profile并刷新生效 source ~/.bashrc文件或者./bash_profile

(3)将HISTIMEFORMAT变量添加到/etc/profile文件中,永久对所有用户生效

echo'HISTTIMEFORMAT="%F %T "'>>~/.bashrc然后生效source /etc/profile

        注意:配置完,会发现怎么时间都一样,这是因为显示的是你头一次设置完参数的时间,这个变量只对设置后的时间有效,以前的就算一样的时间了!

6.6.2 调整history记录的条数

        history命令默认可以保存的命令数是1000,如何调整history的保存条数呢?

(1)查找profile文件

        history命令最大记录数的设置还在profile文件中。使用命令cd /etc进入etc文件

(2)vi profile

        在profile文件中找到配置项HISTSIZE,默认值为1000,按下i进行编辑,编辑为10000甚至更多,按下:wq,保存退出,history的条数设置就完成了。

6.7 man command

Confused about the function of certain Linux commands? Don’t worry, you can easily learn how to use them right from Linux’s shell by using the man command. For instance, entering man tail will show the manual instruction of the tail command.

6.8 echo command

This command is used to move some data into a file. For example, if you want to add the text, “Hello, my name is John” into a file called name.txt, you would type echo Hello, my name is John >> name.txt

        显示环境变量PATH的值:

echo $PATH

6.9 hostname command

If you want to know the name of your host/network simply type hostname. Adding a -i to the end will display the IP address of your network.

6.10 用&&进行多个命令的串行连接

ls&&du 

        以上这样会先执行完ls后再执行du。

6.11 快速清空文件

$ > test.log

: >test.log

ture > test.log

echo “” > test.log

cat /dev/null > test.log

7. Shell

 7.1 linux shell快捷键 

        ctrl+a移到命令行首

        ctrl+c 终止当前运行的命令

        ctrl+d 后台执行命令

        ctrl+e到命令行末

        ctrl+k 删除光标以后

        ctrl+l 清屏

        ctrl+p 查看上一条命令

        ctrl+r 搜索历史命令

        ctrl+u删除从光标以前的

        ctrl+w 删除光标钱一个参数

        ctrl+z 当前进程后台处理

7.2 如何快速查看Linux系统上的Shell类型

        1:查看当前系统中所有可登录shell的类型

        要查看当前系统中所有可登录shell的类型,在/etc/shells配置文件中记录了用户可以登录的shell的具体路径,因此查看这个文件的内容,即可知道当前系统中所支持的所有shell类型。

        2:查看某个用户的Shell类型        

        要查看某个用户的Shell类型,可以在/etc/passwd文件的最后字段查看到某个特定用户的登录Shell类型。如以下示例,执行 cat /etc/passwd | grep ^root 最后一个:号字段显示的即为root用户的登录shell类型,为bash,如下图所示 。

        3. 查看正在运行shell的类型

        要查看当前运行shell的类型,有很多种方法。首先,可以通过$0这个变量来获取当前运行的shell类型。

         其次,也可以通过$这个变量来获取当前运行的shell进程号(PID),然后通过ps命令的-p参数或者直接带进程pid号来反向查出运行的shell类型。

更多推荐

Linux常用命令速查集锦(菜鸟日常生存自救手册)