Linux 基础命令学习

许多 Linus 大神令人眼花缭乱的酷炫操作就是基于这些基本的命令的,既然如此,让我们也来窥探窥探吧。

温馨提示:文章有点长,如果你想查看具体某个命令的用法的话,最好在浏览器 Ctrl + F 搜一下,应该很快能定位到其在文中的位置。

文件管理

awk

awk 是一种处理文本文件的语言,是一个强大的文本分析工具。

Linux 三剑客 grep、sed 和 awk_TomorrowAndTuture的博客-CSDN博客

cat

cat 命令用于连接文件并打印到标准输出设备上。

参数

  • -n 或 --number:由 1 开始对所有输出的行数编号,而且输出有缩进。
  • -b 或 --number-nonblank:和 -n 相似,只不过对于空白行不编号。
  • -s 或 --squeeze-blank:当遇到有连续两行以上的空白行,就代换为一行的空白行。
  • -v 或 --show-nonprinting:使用 ^ 和 M- 符号,除了 LFD 和 TAB 之外。
  • -E 或 --show-ends : 在每行结束处显示 $。
  • -T 或 --show-tabs: 将 TAB 字符显示为 ^I。
  • -A, --show-all:等价于 -vET。
  • -e:等价于"-vE"选项;
  • -t:等价于"-vT"选项;

cat -n textfile1 > textfile2

把 textfile1 的文档内容加上行号后输入 textfile2 这个文档里,空白行也会编号。

# textfile1

hello world
I am Looking

~                                                                                                                      
[root@master shell_learning]# cat -n textfile1 > textfile2
[root@master shell_learning]# cat textfile2
     1	hello world
     2	I am Looking
     3	

cat -b textfile1 textfile2 >> textfile3

把 textfile1 和 textfile2 的文档内容加上行号(空白行不加)之后将内容附加到 textfile3 文档里。

[root@master shell_learning]# cat -b textfile1 textfile2 >> textfile3
[root@master shell_learning]# cat textfile3
     1	hello world
     2	I am Looking

     3	     1	hello world
     4	     2	I am Looking
     5	     3	

cat /dev/null > textfile3

清空 texgfile3 文档内容(很有用的命令)。

[root@master shell_learning]# cat textfile3
     1	hello world
     2	I am Looking

     3	     1	hello world
     4	     2	I am Looking
     5	     3	
[root@master shell_learning]# cat /dev/null > textfile3
[root@master shell_learning]# cat textfile3

cat -s textfile3

当遇到有连续两行以上的空白行,就代换为一行的空白行。

[root@master shell_learning]# cat textfile3
hello world



I am Looking
[root@master shell_learning]# cat -s textfile3 
hello world

I am Looking

cat -e textfile3

在每行结束处显示 $。

[root@master shell_learning]# cat -e textfile3 
hello world$
	$
	$
$
I am Looking$

cat -t textfile3

将 TAB 字符显示为 ^I。

[root@master shell_learning]# cat -t textfile3 
hello world
^I
^I

I am Looking

cat /dev/fd0 > OUTFILE

cat 也可以用来制作镜像文件。

[root@master shell_learning]# cat /dev/fb0 > OUTFILE
[root@master shell_learning]# ll
total 4080
-rw-r--r--. 1 root root 4163040 Aug 22 14:29 OUTFILE
-rwxr-xr-x. 1 root root      98 Aug 16 20:23 test.sh
-rw-r--r--. 1 root root      26 Aug 22 14:23 textfile1
-rw-r--r--. 1 root root      47 Aug 22 14:18 textfile2
-rw-r--r--. 1 root root       0 Aug 22 14:26 textfile3

cat IMG_FILE > /dev/fd0

相反的,可以把镜像文件 image file 写到软盘。

cat >> test.txt <

往 test.txt 里边追加两个 eof 之间内容。


[root@master shell_learning]# cat >> test.txt < hello
heredoc> world
heredoc> eof

cat <<-EOF / cat <

[root@master shell_learning]# cat test.sh
cat <<-EOF
	hello
	world
	Nice
EOF

cat <

chattr/lsattr

chattr命令用于改变文件属性。

这项指令可改变存放在ext2文件系统上的文件或目录属性,这些属性共有以下8种模式:

  1. a:让文件或目录仅供附加用途。
  2. b:不更新文件或目录的最后存取时间。
  3. c:将文件或目录压缩后存放。
  4. d:将文件或目录排除在倾倒操作之外。
  5. i:不得任意更动文件或目录。
  6. s:保密性删除文件或目录。
  7. S:即时更新文件或目录。
  8. u:预防意外删除。

参数:

  • -R 递归处理,将指定目录下的所有文件及子目录一并处理。
  • -v<版本编号> 设置文件或目录版本。
  • -V 显示指令执行过程。
  • +<属性> 开启文件或目录的该项属性。
  • -<属性> 关闭文件或目录的该项属性。
  • =<属性> 指定文件或目录的该项属性。

chattr +i textfile.txt

[root@master shell_learning]# chattr +i textfile.txt 
[root@master shell_learning]# rm textfile.txt
rm: remove regular file ‘textfile.txt’? y
rm: cannot remove ‘textfile.txt’: Operation not permitted
# 设定 +i 之后,连 root 都没法删除,厉害吧!!!
[root@master shell_learning]# lsattr textfile.txt 
----i----------- textfile.txt

[root@master shell_learning]# vim textfile.txt 

hello
hello
world
hello
nice
great
good
nice
good
hello
~                                                                                                                                                 
~                                                                                                                                                                                                                                                                                                
~                                                                                                                                                 
-- INSERT -- W10: Warning: Changing a readonly file 

chattr +a textfile.txt

让某个文件只能往里面追加数据,但不能删除,适用于各种日志文件。

[root@master shell_learning]# chattr +a textfile.txt 

# 设置以后编辑文件无法正常保存
[root@master shell_learning]# vim textfile.txt

hello
hello
world
hello
nice
great
good
nice
tgood
hello
~                                                                                                                                                 
~                                                                                                                                                 
~                                                                                                                                                 
~                                                                                                                                                                                                                                                                                                                                                                                                                                                 
"textfile.txt"                                                                                                                  
"textfile.txt" E212: Can't open file for writing
Press ENTER or type command to continue

# 但是可以正常往文件后边追加内容
[root@master shell_learning]# cat textfile.txt
hello
hello
world
hello
nice
great
good
nice
good
hello
[root@master shell_learning]# echo Looking >> textfile.txt
[root@master shell_learning]# cat textfile.txt
hello
hello
world
hello
nice
great
good
nice
good
hello
Looking

# 取消设置以后可以对文件正常操作
[root@master shell_learning]# chattr -a textfile.txt 

chgrp

chgrp 命令用于变更文件或目录的所属群组。

参数:

  • -c或--changes 效果类似"-v"参数,但仅回报更改的部分。
  • -f或--quiet或--silent  不显示错误信息。
  • -h或--no-dereference  只对符号连接的文件作修改,而不更动其他任何相关文件。
  • -R或--recursive  递归处理,将指定目录下的所有文件及子目录一并处理。
  • -v或--verbose  显示指令执行过程。
  • --help  在线帮助。
  • --reference=<参考文件或目录>  把指定文件或目录的所属群组全部设成和参考文件或目录的所属群组相同。
  • --version  显示版本信息。

chgrp -v looking textfile.txt

[root@master shell_learning]# ll
total 28
-rw-r--r--. 1 root root 13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root root    90 Apr  2 14:28 passwd.txt
-rw-r--r--. 1 root root    56 Aug 24 22:20 textfile.txt
-rw-r--r--. 1 root root   276 Apr 27 14:34 user.txt
[root@master shell_learning]# chgrp -v looking textfile.txt
changed group of ‘textfile.txt’ from root to looking
[root@master shell_learning]# ll
total 28
-rw-r--r--. 1 root root    13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root root       90 Apr  2 14:28 passwd.txt
-rw-r--r--. 1 root looking    56 Aug 24 22:20 textfile.txt
-rw-r--r--. 1 root root      276 Apr 27 14:34 user.txt

chgrp -v --reference=user.txt textfile.txt 

[root@master shell_learning]# ll
total 28
-rw-r--r--. 1 root root    13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root root       90 Apr  2 14:28 passwd.txt
-rw-r--r--. 1 root looking    56 Aug 24 22:20 textfile.txt
-rw-r--r--. 1 root root      276 Apr 27 14:34 user.txt
[root@master shell_learning]# chgrp -v --reference=user.txt textfile.txt 
changed group of ‘textfile.txt’ from looking to root
[root@master shell_learning]# ll
total 28
-rw-r--r--. 1 root root 13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root root    90 Apr  2 14:28 passwd.txt
-rw-r--r--. 1 root root    56 Aug 24 22:20 textfile.txt
-rw-r--r--. 1 root root   276 Apr 27 14:34 user.txt

chmod

chmod 是控制用户对文件的权限的命令。

参数:

  • u 表示该文件的拥有者,g 表示与该文件的拥有者属于同一个群体(group)者,o 表示其他以外的人,a 表示这三者皆是。
  • + 表示增加权限、- 表示取消权限、= 表示唯一设定权限。
  • r 表示可读取,w 表示可写入,x 表示可执行,X 表示只有当该文件是个子目录或者该文件已经被设定过为可执行。
  • -c : 若该文件权限确实已经更改,才显示其更改动作
  • -f : 若该文件权限无法被更改也不要显示错误讯息
  • -v : 显示权限变更的详细资料
  • -R : 对目前目录下的所有文件与子目录进行相同的权限变更(即以递回的方式逐个变更)
  • --help : 显示辅助说明
  • --version : 显示版本

chmod ugo+r textfile.txt

将文件 textfile.txt 设为所有人皆可读取 

[root@master shell_learning]# ll
total 28
-rw-r--r--. 1 root root 13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root root    90 Apr  2 14:28 passwd.txt
--w-------. 1 root root    56 Aug 24 22:20 textfile.txt
-rw-r--r--. 1 root root   276 Apr 27 14:34 user.txt
[root@master shell_learning]# chmod a+r textfile.txt 
[root@master shell_learning]# ll
total 28
-rw-r--r--. 1 root root 13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root root    90 Apr  2 14:28 passwd.txt
-rw-r--r--. 1 root root    56 Aug 24 22:20 textfile.txt
-rw-r--r--. 1 root root   276 Apr 27 14:34 user.txt

chmod ug+w,o-w file1.txt file2.txt

将文件 file1.txt 与 file2.txt 设为该文件拥有者,与其所属同一个群体者可写入,但其他以外的人则不可写入。

[root@master shell_learning]# ll
total 28
-rw-r--r--. 1 root root     0 Aug 24 23:19 file1.txt
-rw-r--r--. 1 root root     0 Aug 24 23:19 file2.txt
-rw-r--r--. 1 root root 13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root root    90 Apr  2 14:28 passwd.txt
-rw-r--r--. 1 root root    56 Aug 24 22:20 textfile.txt
-rw-r--r--. 1 root root   276 Apr 27 14:34 user.txt
[root@master shell_learning]# chmod ug+w,o-w file1.txt file2.txt
[root@master shell_learning]# ll
total 28
-rw-rw-r--. 1 root root     0 Aug 24 23:19 file1.txt
-rw-rw-r--. 1 root root     0 Aug 24 23:19 file2.txt
-rw-r--r--. 1 root root 13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root root    90 Apr  2 14:28 passwd.txt
-rw-r--r--. 1 root root    56 Aug 24 22:20 textfile.txt
-rw-r--r--. 1 root root   276 Apr 27 14:34 user.txt

chmod u+x world.py

将 world.py 设定为只有该文件拥有者可以执行。

[root@master python3_learning]# ll
total 8
-rw-r--r--. 1 root root 439 Apr 28 13:39 ip-address.py
-rw-r--r--. 1 root root 149 Aug 15 20:38 world.py
[root@master python3_learning]# chmod u+x world.py 
[root@master python3_learning]# ll
total 8
-rw-r--r--. 1 root root 439 Apr 28 13:39 ip-address.py
-rwxr--r--. 1 root root 149 Aug 15 20:38 world.py

chmod -R a+r *

将目前目录下的所有文件与子目录皆设为任何人可读取 。

[root@master shell_learning]# chmod -R a+r *
[root@master shell_learning]# ll
total 28
-rw-rw-r--. 1 root root     0 Aug 24 23:19 file1.txt
-rw-rw-r--. 1 root root     0 Aug 24 23:19 file2.txt
-rw-r--r--. 1 root root 13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root root    90 Apr  2 14:28 passwd.txt
-rw-r--r--. 1 root root    56 Aug 24 22:20 textfile.txt
-rw-r--r--. 1 root root   276 Apr 27 14:34 user.txt

chmod 777 file [or] chmod ug=rwx,o=x file

若用 chmod 4755 filename可使此程序具有 root 的权限,chmod 4755 与 chmod 755 的区别在于开头多了一位,这个 4 表示其他用户执行文件时,具有与所有者相当的权限。

例如:root 用户创建了一个上网认证程序 netlogin,如果其他用户要上网也要用到这个程序,那就需要 root 用户运行 chmod 755 netlogin 命令使其他用户也能运行 netlogin。但是 netlogin 执行时可能需要访问一些只有 root 用户才有权访问的文件,那么其他用户执行 netlogin 时可能因为权限不够还是不能上网。这种情况下,就可以用 chmod 4755 netlogin 设置其他用户在执行 netlogin 也有root用户的权限,从而顺利上网。

chown

利用 chown 将指定文件的拥有者改为指定的用户或组,用户可以是用户名或者用户 ID;组可以是组名或者组 ID;文件是以空格分开的要改变权限的文件列表,支持通配符。一般来说,这个指令只有是由系统管理者(root)所使用,一般使用者没有权限可以改变别人的文件拥有者,也没有权限把自己的文件拥有者改设为别人。只有系统管理者(root)才有这样的权限。

参数:

  • user : 新的文件拥有者的使用者 ID
  • group : 新的文件拥有者的使用者组(group)
  • -c : 显示更改的部分的信息
  • -f : 忽略错误信息
  • -h :修复符号链接
  • -v : 显示详细的处理信息
  • -R : 处理指定目录以及其子目录下的所有文件
  • --help : 显示辅助说明
  • --version : 显示版本

chown looking:looking textfile.txt

[root@master shell_learning]# ll
total 28
-rw-rw-r--. 1 root root     0 Aug 24 23:19 file1.txt
-rw-rw-r--. 1 root root     0 Aug 24 23:19 file2.txt
-rw-r--r--. 1 root root 13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root root    90 Apr  2 14:28 passwd.txt
-rw-r--r--. 1 root root    56 Aug 24 22:20 textfile.txt
-rw-r--r--. 1 root root   276 Apr 27 14:34 user.txt
[root@master shell_learning]# chown looking:looking textfile.txt
[root@master shell_learning]# ll
total 28
-rw-rw-r--. 1 root    root        0 Aug 24 23:19 file1.txt
-rw-rw-r--. 1 root    root        0 Aug 24 23:19 file2.txt
-rw-r--r--. 1 root    root    13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root    root       90 Apr  2 14:28 passwd.txt
-rw-r--r--. 1 looking looking    56 Aug 24 22:20 textfile.txt
-rw-r--r--. 1 root    root      276 Apr 27 14:34 user.txt

chown -R root:looking * 

[root@master shell_learning]# chown -R root:looking *
[root@master shell_learning]# ll
total 28
-rw-rw-r--. 1 root looking     0 Aug 24 23:19 file1.txt
-rw-rw-r--. 1 root looking     0 Aug 24 23:19 file2.txt
-rw-r--r--. 1 root looking 13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root looking    90 Apr  2 14:28 passwd.txt
-rw-r--r--. 1 root looking    56 Aug 24 22:20 textfile.txt
-rw-r--r--. 1 root looking   276 Apr 27 14:34 user.txt

cksum

cksum 命令用于检查文件的 CRC 是否正确。确保文件从一个系统传输到另一个系统的过程中不被损坏。CRC 是一种排错检查方式,该校验法的标准由 CCITT 所指定,至少可检测到 99.998% 的已知错误。

参数

  • --help:在线帮助。
  • --version:显示版本信息。
  • 文件…:需要进行检查的文件路径
[root@master shell_learning]# cksum textfile.txt 
1594075638 56 textfile.txt

cmp

cmp 命令用于比较两个文件是否有差异。当相互比较的两个文件完全一样时,则该指令不会显示任何信息。若发现有所差异,预设会标示出第一个不同之处的字符和列数编号。若不指定任何文件名称或是所给予的文件名为"-",则 cmp 指令会从标准输入设备读取数据。

参数

  • -c或--print-chars  除了标明差异处的十进制字码之外,一并显示该字符所对应字符。
  • -i<字符数目>或--ignore-initial=<字符数目>  指定一个数目。
  • -l或--verbose  标示出所有不一样的地方。
  • -s或--quiet或--silent  不显示错误信息。
  • -v或--version  显示版本信息。
  • --help  在线帮助。

cmp file1.txt file2.txt

[root@master shell_learning]# cat file1.txt 
hello
hello world
[root@master shell_learning]# cat file2.txt 
hello
hello
hello world
[root@master shell_learning]# cmp file1.txt file2.txt 
file1.txt file2.txt differ: byte 12, line 2

cmp -c file1.txt file2.txt

[root@master shell_learning]# cmp -c file1.txt file2.txt 
file1.txt file2.txt differ: byte 12, line 2 is  40    12 ^J

cmp -l file1.txt file2.txt  

[root@master shell_learning]# cmp -l file1.txt file2.txt 
12  40  12
13 167 150
14 157 145
15 162 154
17 144 157
18  12  40
cmp: EOF on file1.txt

cp

cp 命令主要用于复制文件或目录。

参数

  • -a:此选项通常在复制目录时使用,它保留链接、文件属性,并复制目录下的所有内容。其作用等于dpR参数组合。
  • -d:复制时保留链接。这里所说的链接相当于Windows系统中的快捷方式。
  • -f:覆盖已经存在的目标文件而不给出提示。
  • -i:与-f选项相反,在覆盖目标文件之前给出提示,要求用户确认是否覆盖,回答"y"时目标文件将被覆盖。
  • -p:除复制文件的内容外,还把修改时间和访问权限也复制到新文件中。
  • -r:若给出的源文件是一个目录文件,此时将复制该目录下所有的子目录和文件。
  • -l:不复制文件,只是生成链接文件。

cp ../out.txt ./

[root@master test1_dir]# ls
[root@master test1_dir]# cp ../out.txt ./
[root@master test1_dir]# ls
out.txt

cp -r test1_dir/ test2_dir/ 

[root@master shell_learning]# cp -r test1_dir/ test2_dir/
[root@master shell_learning]# ls test2_dir/
test1_dir

cut

cut 命令从文件的每一行剪切字节、字符和字段并将这些字节、字符和字段写至标准输出。如果不指定 File 参数,cut 命令将读取标准输入。必须指定 -b、-c 或 -f 标志之一。

参数:

  • -b :以字节为单位进行分割。这些字节位置将忽略多字节字符边界,除非也指定了 -n 标志。
  • -c :以字符为单位进行分割。
  • -d :自定义分隔符,默认为制表符。
  • -f :与-d一起使用,指定显示哪个区域。
  • -n :取消分割多字节字符。仅和 -b 标志一起使用。如果字符的最后一个字节落在由 -b 标志的 List 参数指示的
    范围之内,该字符将被写出;否则,该字符将被排除。

cat textfile.txt | cut -c 3

root@master ~/w/shell_learning# cat textfile.txt
hello world
hello nice
great work
root@master ~/w/shell_learning# cat textfile.txt | cut -c 3
l
l
e

 cat textfile.txt | cut -d ' ' -f 2

root@master ~/w/shell_learning# cat textfile.txt
hello world
hello nice
great work
root@master ~/w/shell_learning# cat textfile.txt | cut -d ' ' -f 1
hello
hello
great
root@master ~/w/shell_learning# cat textfile.txt | cut -d ' ' -f 2
world
nice
work

diff

diff 以逐行的方式,比较文本文件的异同处。如果指定要比较目录,则 diff 会比较目录中相同文件名的文件,但不会比较其中子目录。

参数

  • -<行数>  指定要显示多少行的文本。此参数必须与-c或-u参数一并使用。
  • -a或--text  diff 预设只会逐行比较文本文件。
  • -b或--ignore-space-change  不检查空格字符的不同。
  • -B或--ignore-blank-lines  不检查空白行。
  • -c  显示全部内文,并标出不同之处。
  • -C<行数>或--context<行数>  与执行"-c-<行数>"指令相同。
  • -d或--minimal  使用不同的演算法,以较小的单位来做比较。
  • -D<巨集名称>或ifdef<巨集名称>  此参数的输出格式可用于前置处理器巨集。
  • -e或--ed  此参数的输出格式可用于ed的script文件。
  • -f或-forward-ed  输出的格式类似ed的script文件,但按照原来文件的顺序来显示不同处。
  • -H或--speed-large-files  比较大文件时,可加快速度。
  • -l<字符或字符串>或--ignore-matching-lines<字符或字符串>  若两个文件在某几行有所不同,而这几行同时都包含了选项中指定的字符或字符串,则不显示这两个文件的差异。
  • -i或--ignore-case  不检查大小写的不同。
  • -l或--paginate  将结果交由pr程序来分页。
  • -n或--rcs  将比较结果以RCS的格式来显示。
  • -N或--new-file  在比较目录时,若文件A仅出现在某个目录中,预设会显示:
  • Only in目录:文件A若使用-N参数,则diff会将文件A与一个空白的文件比较。
  • -p  若比较的文件为C语言的程序码文件时,显示差异所在的函数名称。
  • -P或--unidirectional-new-file  与-N类似,但只有当第二个目录包含了一个第一个目录所没有的文件时,才会将这个文件与空白的文件做比较。
  • -q或--brief  仅显示有无差异,不显示详细的信息。
  • -r或--recursive  比较子目录中的文件。
  • -s或--report-identical-files  若没有发现任何差异,仍然显示信息。
  • -S<文件>或--starting-file<文件>  在比较目录时,从指定的文件开始比较。
  • -t或--expand-tabs  在输出时,将tab字符展开。
  • -T或--initial-tab  在每行前面加上tab字符以便对齐。
  • -u,-U<列数>或--unified=<列数>  以合并的方式来显示文件内容的不同。
  • -v或--version  显示版本信息。
  • -w或--ignore-all-space  忽略全部的空格字符。
  • -W<宽度>或--width<宽度>  在使用-y参数时,指定栏宽。
  • -x<文件名或目录>或--exclude<文件名或目录>  不比较选项中所指定的文件或目录。
  • -X<文件>或--exclude-from<文件>  您可以将文件或目录类型存成文本文件,然后在=<文件>中指定此文本文件。
  • -y或--side-by-side  以并列的方式显示文件的异同之处。
  • --help  显示帮助。
  • --left-column  在使用-y参数时,若两个文件某一行内容相同,则仅在左侧的栏位显示该行内容。
  • --suppress-common-lines  在使用-y参数时,仅显示不同之处。

diff file1.txt file2.txt

[root@master shell_learning]# cat file1.txt 
hello
hello world
[root@master shell_learning]# cat file2.txt 
hello
hello
hello world
[root@master shell_learning]# diff file1.txt file2.txt 
1a2
> hello

diff file1.txt file2.txt -y -W 50

[root@master shell_learning]# diff file1.txt file2.txt -y -W 50
hello			hello
		      >	hello
hello world		hello world

diff file2.txt file1.txt -y -W 50

[root@master shell_learning]# diff file2.txt file1.txt -y -W 50
hello			hello
hello		      <
hello world		hello world

说明:

  • "|"  表示前后 2 个文件内容有不同
  • "<" 表示后面文件比前面文件少了 1 行内容
  • ">" 表示后面文件比前面文件多了 1 行内容

diffstat

diffstat 命令根据 diff 的比较结果,显示统计数字。diffstat 读取 diff 的输出结果,然后统计各文件的插入,删除,修改等差异。

参数

  • -n<文件名长度>  指定文件名长度,指定的长度必须大于或等于所有文件中最长的文件名。
  • -p<文件名长度>  与-n参数相同,但此处的<文件名长度>包括了文件的路径。
  • -w  指定输出时栏位的宽度。
  • -V  显示版本信息。

diff file1.txt file2.txt

[root@master shell_learning]# cat file1.txt 
abc  
def  
ghi  
jkl  
mno  
pqr  
stu  
vws 
[root@master shell_learning]# cat file2.txt 
abc  
def  
ghi  
jkl  
mno
[root@master shell_learning]# diff file1.txt file2.txt | diffstat
 unknown |    5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)
[root@master shell_learning]# diff file1.txt file2.txt
5,8c5
< mno  
< pqr  
< stu  
< vws 
---
> mno

echo

echo "It is a test"



显示字符串

[root@master ~]# echo "It is a test"
It is a test

echo "$name It is a test"

显示变量

[root@master ~]# read name
OK

[root@master ~]# echo "$name It is a test"
OK It is a test

echo -e "OK! \n"

开启转义

[root@master ~]# echo -e "OK! \n" # -e 开启转义
OK!

[root@master ~]# echo "OK! \n" # 未开启转义
OK! \n



echo "It is a test" > myfile

结果定向至文件

[root@master ~]# echo "It is a test" > myfile
[root@master ~]# cat myfile
It is a test

echo "It is a test" >> myfile

结果追加至文件

[root@master ~]# echo "It is a test" >> myfile
[root@master ~]# cat myfile
It is a test

echo '$name\"'

原样输出字符串

[root@master ~]# name="Looking"
[root@master ~]# echo '$name\"'
$name\"

[root@master ~]# echo "$name\""
Looking"



echo `date`

显示命令执行结果

注意: 这里使用的是反引号 `(esc 按键下边那个), 而不是单引号 '。

[root@master ~]# date
Sun Aug 16 22:31:35 CST 2020

[root@master ~]# echo `date`
Sun Aug 16 22:31:46 CST 2020

file

file 命令用于辨识文件类型。

参数

  • -b  列出辨识结果时,不显示文件名称。
  • -c  详细显示指令执行过程,便于排错或分析程序执行的情形。
  • -f<名称文件>  指定名称文件,其内容有一个或多个文件名称时,让file依序辨识这些文件,格式为每列一个文件名称。
  • -L  直接显示符号连接所指向的文件的类别。
  • -m<魔法数字文件>  指定魔法数字文件。
  • -v  显示版本信息。
  • -z  尝试去解读压缩文件的内容。
  • [文件或目录...] 要确定类型的文件列表,多个文件之间使用空格分开,可以使用shell通配符匹配多个文件。

file textfile.txt

[root@master shell_learning]# file textfile.txt 
textfile.txt: ASCII text

file -b textfile.txt

[root@master shell_learning]# file -b textfile.txt 
ASCII text

file -i textfile.txt 

[root@master shell_learning]# file -bi textfile.txt 
text/plain; charset=us-ascii
[root@master shell_learning]# file -bi textfile.txt 
text/plain; charset=us-ascii

file hello.rb.link

[root@master workspace]# file hello.rb.link
hello.rb.link: symbolic link to `hello.rb'

file -L hello.rb.link

[root@master workspace]# file -L hello.rb.link
hello.rb.link: Ruby script, ASCII text executable

file ruby_learning/

[root@master workspace]# file ruby_learning/
ruby_learning/: directory

find

find 命令用来在指定目录下查找文件。任何位于参数之前的字符串都将被视为欲查找的目录名。如果使用该命令时,不设置任何参数,则 find 命令将在当前目录下查找子目录与文件。并且将查找到的子目录和文件全部进行显示。

参数:

find 根据下列规则判断 path 和 expression,在命令列上第一个 - ( ) , ! 之前的部份为 path,之后的是 expression。如果 path 是空字串则使用目前路径,如果 expression 是空字串则使用 -print 为预设 expression。

expression 中可使用的选项有二三十个之多,在此只介绍最常用的部份。

  • -mount, -xdev : 只检查和指定目录在同一个文件系统下的文件,避免列出其它文件系统中的文件
  • -amin n : 在过去 n 分钟内被读取过
  • -anewer file : 比文件 file 更晚被读取过的文件
  • -atime n : 在过去n天内被读取过的文件
  • -cmin n : 在过去 n 分钟内被修改过
  • -cnewer file :比文件 file 更新的文件
  • -ctime n : 在过去n天内被修改过的文件
  • -empty : 空的文件-gid n or -group name : gid 是 n 或是 group 名称是 name
  • -ipath p, -path p : 路径名称符合 p 的文件,ipath 会忽略大小写
  • -name name, -iname name : 文件名称符合 name 的文件。iname 会忽略大小写
  • -size n : 文件大小 是 n 单位,b 代表 512 位元组的区块,c 表示字元数,k 表示 kilo bytes,w 是二个位元组。
  • -type c : 文件类型是 c 的文件。
  • d: 目录
  • c: 字型装置文件
  • b: 区块装置文件
  • p: 具名贮列
  • f: 一般文件
  • l: 符号连结
  • s: socket
  • -pid n : process id 是 n 的文件

find . -name "*.py"

将目前目录及其子目录下所有扩展名是 py 的文件列出来

[root@master workspace]# find . -name "*.py"
./python3_learning/world.py
./python3_learning/ip-address.py
./ip-address.py
./test.py
./world.py

find . -type f 

将目前目录其其下子目录中所有一般文件列出

[root@master shell_learning]# find . -type f
./passwd.txt
./user.txt
./get-docker.sh
./textfile.txt
./file1.txt
./file2.txt
./test.rb

find . -ctime -20

将目前目录及其子目录下所有最近 20 天内更新过的文件列出

[root@master shell_learning]# find . -ctime -20
.
./passwd.txt
./user.txt
./get-docker.sh
./textfile.txt
./file1.txt
./file2.txt
./test.rb

find /var/log -type f -mtime +7 -ok rm {} \; 

查找 /var/log 目录中更改时间在7日以前的普通文件,并在删除之前询问它们

[root@master shell_learning]# find /var/log -type f -mtime +7 -ok rm {} \;
< rm ... /var/log/tallylog > ? y
< rm ... /var/log/grubby_prune_debug > ? y
< rm ... /var/log/tuned/tuned.log.1 > ? 

find . -type f -perm 644 -exec ls -l {} \;

查找前目录中文件属主具有读、写权限,并且文件所属组的用户和其他用户具有读权限的文件

[root@master shell_learning]# find . -type f -perm 644 -exec ls -l {} \;
-rw-r--r--. 1 root looking 90 Apr  2 14:28 ./passwd.txt
-rw-r--r--. 1 root looking 276 Apr 27 14:34 ./user.txt
-rw-r--r--. 1 root looking 13185 Sep 18  2019 ./get-docker.sh
-rw-r--r--. 1 root looking 56 Aug 24 22:20 ./textfile.txt
-rw-r--r--. 1 root root 47 Sep  1 22:24 ./test.rb

find / -type f -size 0 -exec ls -l {} \;

查找系统中所有文件长度为 0 的普通文件,并列出它们的完整路径(根目录下的话这个就有点多了)

[root@master shell_learning]# find . -type f -size 0 -exec ls -l {} \;
...
-rw-r--r--. 1 root root 0 Sep  1 23:06 /proc/sys/net/core/default_qdisc
-rw-r--r--. 1 root root 0 Sep  1 23:06 /proc/sys/net/core/dev_weight
-rw-r--r--. 1 root root 0 Sep  1 23:06 /proc/sys/net/core/dev_weight_rx_bias
-rw-r--r--. 1 root root 0 Sep  1 23:06 /proc/sys/net/core/dev_weight_tx_bias
-rw-r--r--. 1 root root 0 Sep  1 23:06 /proc/sys/net/core/message_burst
-rw-r--r--. 1 root root 0 Sep  1 23:06 /proc/sys/net/core/message_cost
-rw-r--r--. 1 root root 0 Sep  1 23:06 /proc/sys/net/core/netdev_budget
...

ln

ln 命令是一个非常重要命令,它的功能是为某一个文件在另外一个位置建立一个同步的链接。当我们需要在不同的目录,用到相同的文件时,我们不需要在每一个需要的目录下都放一个必须相同的文件,我们只要在某个固定的目录,放上该文件,然后在 其它的目录下用 ln 命令链接(link)它就可以,不必重复的占用磁盘空间。

命令功能 :
Linux文件系统中,有所谓的链接(link),我们可以将其视为档案的别名,而链接又可分为两种 : 硬链接(hard link)与软链接(symbolic link),硬链接的意思是一个档案可以有多个名称,而软链接的方式则是产生一个特殊的档案,该档案的内容是指向另一个档案的位置。硬链接是存在同一个文件系统中,而软链接却可以跨越不同的文件系统。

不论是硬链接或软链接都不会将原本的档案复制一份,只会占用非常少量的磁盘空间。

软链接

  • 1.软链接,以路径的形式存在。类似于Windows操作系统中的快捷方式
  • 2.软链接可以 跨文件系统 ,硬链接不可以
  • 3.软链接可以对一个不存在的文件名进行链接
  • 4.软链接可以对目录进行链接

硬链接

  • 1.硬链接,以文件副本的形式存在。但不占用实际空间。
  • 2.不允许给目录创建硬链接
  • 3.硬链接只有在同一个文件系统中才能创建

参数

  • -b 删除,覆盖以前建立的链接
  • -d 允许超级用户制作目录的硬链接
  • -f 强制执行
  • -i 交互模式,文件存在则提示用户是否覆盖
  • -n 把符号链接视为一般目录
  • -s 软链接(符号链接)
  • -v 显示详细的处理过程

ln textfile.txt textfile2.txt

[root@master shell_learning]# ln textfile.txt textfile2.txt
[root@master shell_learning]# ls
file1.txt  file2.txt  get-docker.sh  passwd.txt  test.rb  textfile.txt  textfile2.txt user.txt

ln -s textfile.txt textfile.txt.link 

[root@master shell_learning]# ln -s textfile.txt textfile.txt.link
[root@master shell_learning]# ls
file1.txt  file2.txt  get-docker.sh  passwd.txt  test.rb  textfile2.txt  textfile.txt  textfile.txt.link  user.txt

less

可以使用 less 随意浏览文件,而 more 仅能向前移动,却不能向后移动,而且 less 在查看之前不会加载整个文件。

参数

  • -b <缓冲区大小> 设置缓冲区的大小
  • -e 当文件显示结束后,自动离开
  • -f 强迫打开特殊文件,例如外围设备代号、目录和二进制文件
  • -g 只标志最后搜索的关键词
  • -i 忽略搜索时的大小写
  • -m 显示类似more命令的百分比
  • -N 显示每行的行号
  • -o <文件名> 将less 输出的内容在指定文件中保存起来
  • -Q 不使用警告音
  • -s 显示连续空行为一行
  • -S 行过长时间将超出部分舍弃
  • -x <数字> 将"tab"键显示为规定的数字空格
  • /字符串:向下搜索"字符串"的功能
  • ?字符串:向上搜索"字符串"的功能
  • n:重复前一个搜索(与 / 或 ? 有关)
  • N:反向重复前一个搜索(与 / 或 ? 有关)
  • b 向上翻一页
  • d 向后翻半页
  • h 显示帮助界面
  • Q 退出less 命令
  • u 向前滚动半页
  • y 向前滚动一行
  • 空格键 滚动一页
  • 回车键 滚动一行
  • [pagedown]: 向下翻动一页
  • [pageup]: 向上翻动一页

less iperf.json

[root@master shell_learning]# less iperf.json
{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 3330,
    "max_score": 2.8104148,
    "hits": [
      {
        "_index": "jobs1",
        "_type": "_doc",
        "_id": "5142",
        "_score": 2.8104148,
iperf.json lines 1-18/825 1%

history | less

[root@master shell_learning]# history | less 
 2789  cd workspace
 2794  less -m iperf.json
 2796  more iperf.json
 2797  ps -ef|less
 2798  ps -ef
 2801  ll
 2802  less -n iperf.json
 2804  qq
 2806  vim test.md
 2807  ls
 2808  vim input.json
 2809  ls
 2810  less -N iperf.json
 2811  less iperf.json
 2812  ps -ef | less

less iperf.yaml iperf.json

[root@master shell_learning]# less iperf.yaml iperf.json
{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 3330,
    "max_score": 2.8104148,
    "hits": [
      {
        "_index": "jobs1",
        "_type": "_doc",
        "_id": "5142",
        "_score": 2.8104148,
iperf.json (file 2 of 2) lines 1-18/825 1%

说明:

  • 输入 :n 后,切换到下一个文件 iperf.json
  • 输入 :p 后,切换到上一个文件 iperf.yaml

1. 全屏导航

  • ctrl + F - 向前移动一屏(Forward)
  • ctrl + B - 向后移动一屏(Backward)
  • ctrl + D - 向前移动半屏(Down)
  • ctrl + U - 向后移动半屏(Up)

2. 单行导航

  • j - 向前移动一行
  • k - 向后移动一行

3. 其它导航

  • G - 移动到最后一行
  • g - 移动到第一行
  • q / ZZ - 退出 less 命令

4. 其它有用的命令

  • v - 使用配置的编辑器编辑当前文件
  • h - 显示 less 的帮助文档
  • &pattern - 仅显示匹配模式的行,而不是整个文件

more

more 命令类似 cat ,不过会以一页一页的形式显示,更方便使用者逐页阅读,而最基本的指令就是按空白键(space)就往下一页显示,按 b 键就会往回(back)一页显示,按回车键(Enter)往下一行显示。

more [-dlfpcsu] [-num] [+/pattern] [+linenum] [fileNames..]

参数

  • -num 一次显示的行数
  • -d 提示使用者,在画面下方显示 [Press space to continue, 'q' to quit.] ,如果使用者按错键,则会显示 [Press 'h' for instructions.] 而不是 '哔' 声
  • -l 取消遇见特殊字元 ^L(送纸字元)时会暂停的功能
  • -f 计算行数时,以实际上的行数,而非自动换行过后的行数(有些单行字数太长的会被扩展为两行或两行以上)
  • -p 不以卷动的方式显示每一页,而是先清除萤幕后再显示内容
  • -c 跟 -p 相似,不同的是先显示内容再清除其他旧资料
  • -s 当遇到有连续两行以上的空白行,就代换为一行的空白行
  • -u 不显示下引号 (根据环境变数 TERM 指定的 terminal 而有所不同)
  • +/pattern 在每个文档显示前搜寻该字串(pattern),然后从该字串之后开始显示
  • +num 从第 num 行开始显示
  • fileNames 欲显示内容的文档,可为复数个数

常用操作命令:

  • Enter 向下 n 行,默认为 1 行
  • Ctrl+F 向下滚动一屏
  • 空格键 向下滚动一屏
  • Ctrl+B 返回上一屏
  • = 输出当前行的行号
  • :f 输出文件名和当前行的行号
  • V 调用 vi 编辑器
  • ! 命令 调用 Shell,并执行命令
  • q 退出 more

mv

mv 命令用来为文件或目录改名、或将文件或目录移入其它位置。

mv [options] source dest
mv [options] source... directory

参数

  • -b: 当目标文件或目录存在时,在执行覆盖前,会为其创建一个备份。
  • -i: 如果指定移动的源目录或文件与目标的目录或文件同名,则会先询问是否覆盖旧文件,输入 y 表示直接覆盖,输入 n 表示取消该操作。
  • -f: 如果指定移动的源目录或文件与目标的目录或文件同名,不会询问,直接覆盖旧文件。
  • -n: 不要覆盖任何已存在的文件或目录。
  • -u:当源文件比目标文件新或者目标文件不存在时,才执行移动操作。

mv out.txt in.txt

[root@master shell_learning]# ls
file1  file2  out.txt  test.sh  test.txt
[root@master shell_learning]# mv out.txt in.txt
[root@master shell_learning]# ls
file1  file2  in.txt  test.sh  test.txt

mv info/ logs

将 info 目录放入 logs 目录中。注意,如果 logs 目录不存在,则该命令将 info 改名为 logs。

[root@master shell_learning]# mkdir info
[root@master shell_learning]# ls
file1  file2  info  in.txt  test.sh  test.txt
[root@master shell_learning]# mv info/ logs
[root@master shell_learning]# ls
file1  file2  in.txt  logs  test.sh  test.txt

[root@master shell_learning]# mkdir info   
[root@master shell_learning]# mv info/ logs
[root@master shell_learning]# ls
file1  file2  in.txt  logs  test.sh  test.txt
[root@master shell_learning]# cd logs
[root@master logs]# ls
info

mv ../test.txt .

lukaiyi@crystal ~/workspace/shell_learning/logs% mv ../test.txt .
lukaiyi@crystal ~/workspace/shell_learning/logs% ls
info  test.txt
lukaiyi@crystal ~/workspace/shell_learning/logs% cd ..
lukaiyi@crystal ~/workspace/shell_learning% ls
file1  file2  in.txt  logs  test.sh

目标目录与原目录一致,指定了新文件名,效果就是仅仅重命名。

mv  /home/ffxhd/a.txt   /home/ffxhd/b.txt  

目标目录与原目录不一致,没有指定新文件名,效果就是仅仅移动。

mv  /home/ffxhd/a.txt   /home/ffxhd/test/ 

目标目录与原目录一致, 指定了新文件名,效果就是:移动 + 重命名。

mv  /home/ffxhd/a.txt   /home/ffxhd/test/c.txt

paste

paste 指令会把每个文件以列对列的方式,一列列地加以合并。

参数

  • -d<间隔字符>或--delimiters=<间隔字符>  用指定的间隔字符取代跳格字符。
  • -s或--serial  串列进行而非平行处理。
  • --help  在线帮助。
  • --version  显示帮助信息。
  • [文件…] 指定操作的文件路径

paste file1 file2

[root@master shell_learning]# cat file1
df
dfd
world
[root@master shell_learning]# cat file2
df
dfd
hello
[root@master shell_learning]# paste file1 file2   
df	    df
dfd	    dfd
world	hello

paste -s file1 file2 

[root@master shell_learning]# cat file1
df
dfd
world
[root@master shell_learning]# cat file2
df
dfd
hello
[root@master shell_learning]# paste -s file1 file2
df	dfd	world
df	dfd	hello

rm

rm 命令用于删除一个文件或者目录。

参数

  • -i 删除前逐一询问确认。
  • -f 即使原档案属性设为唯读,亦直接删除,无需逐一确认(--force 强制)。
  • -r 将目录及以下之档案亦逐一删除(--recursive 递归)。

rm -rf /

小朋友,你试过 rm -rf / 这类让人惊恐不安的命令吗?我以前一直以为这只是个段子,直到...。就算你很好奇的话,也千万别拿你的 root 账号试哟(普通账号其实应该没那个权限),如果你用 root 试过了,记得给我贴个图:)(我也很好奇在 root 下会怎么样,但是又没那个胆 )。

[looking@master /]$ rm -rf /
rm: it is dangerous to operate recursively on ‘/’
rm: use --no-preserve-root to override this failsafe

# 哈哈,操作系统已经很郑重其事的在警告你了,回头是岸呀!

后来我实在是太好奇了,于是乎完整克隆了一个虚拟机来试验(结局早已注定)。现在大多数发行版都有了根目录保护机制,所以要加 --no-preserve-root 才可以正常运行,这其实也算是一种防止误操作的手段(各 Linux 发行版的内心独白:毕竟保护选项这么长,你要再误操作的话,总不至于还是我的锅吧?):

[root@slave ~]# cd /
[root@slave /]# rm --no-preserve-root -rf /
# 然后像下面这种一阵刷屏
rm: cannot remove ‘/proc/1447/task/1672/syscall’: Permission denied
rm: cannot remove ‘/proc/1447/task/1672/cmdline’: Permission denied
rm: cannot remove ‘/proc/1447/task/1672/stat’: Permission denied
rm: cannot remove ‘/proc/1447/task/1672/statm’: Permission denied
rm: cannot remove ‘/proc/1447/task/1672/maps’: Permission denied
rm: cannot remove ‘/proc/1447/task/1672/children’: Permission denied
rm: cannot remove ‘/proc/1447/task/1672/numa_maps’: Permission denied
rm: cannot remove ‘/proc/1447/task/1672/mem’: Permission denied
rm: cannot remove ‘/proc/1447/task/1672/cwd’: Permission denied
rm: cannot remove ‘/proc/1447/task/1672/root’: Permission denied
...
rm: cannot remove ‘/sys/module/nf_conntrack_ipv6/refcnt’: Operation not permitted
rm: cannot remove ‘/sys/module/nf_conntrack_ipv6/uevent’: Operation not permitted
rm: cannot remove ‘/sys/module/nf_conntrack_ipv6/holders’: Operation not permitted
rm: cannot remove ‘/sys/hypervisor’: Operation not permitted

[root@slave /]# pwd
/
[root@slave /]# ls
-bash: /usr/bin/ls: No such file or directory


rm  textfile1

一般性删除,确认删除的话输入 y 回车。

[root@master shell_learning]# rm textfile1
rm: remove regular file ‘textfile1’? 

rm [-r] test_directory

[root@master shell_learning]# rm test_directory/
rm: cannot remove ‘test_directory/’: Is a directory
[root@master shell_learning]# rm -r test_directory/
rm: remove directory ‘test_directory/’? 

rm  -r  * 

删除当前目录下的所有文件及目录(这个至少会询问),如果你用 rm  -rf  * 的话,请慎用。

[root@master shell_learning]# rm -r *
rm: remove directory ‘test’? y
rm: remove regular file ‘test.sh’? y
rm: remove regular file ‘textfile2’? y
rm: remove regular file ‘textfile3’? y

[root@master shell_learning]# ll
total 0

split

split 命令用于将一个文件分割成数个较小的文件,默认情况下按照每 1000 行切割成一个小文件。若所给予的文件名为 -,则指令会从标准输入设备读取数据。

参数

  • -<行数> : 指定每多少行切成一个小文件
  • -b<字节> : 指定每多少字节切成一个小文件
  • --help : 在线帮助
  • --version : 显示版本信息
  • -C<字节> : 与参数"-b"相似,但是在切 割时将尽量维持每行的完整性
  • [输出文件名] : 设置切割后文件的前置文件名, split会自动在前置文件名后再加上编号

split -2 test.sh

[root@master shell_learning]# cat test.sh
pkgs=(
	
	world
)
echo $pkgs[@]
echo $@
[root@master shell_learning]# split -2 test.sh
[root@master shell_learning]# ls
file1  file2  in.txt  logs  test.sh  xaa  xab  xac
[root@master shell_learning]# cat xaa
pkgs=(
	
[root@master shell_learning]# cat xab
	world
)
[root@master shell_learning]# cat xac
echo $pkgs[@]
echo $@

split -2 - 

[root@master shell_learning]# split -2 -
helo
world
df
df
^C

[root@master shell_learning]# ls
file1  file2  in.txt  logs  log.txt  test.sh  test.txt  ttt.txt  xaa  xab

[root@master shell_learning]# cat xaa
helo
world

[root@master shell_learning]# cat xab
df
df

tee

tee 指令会从标准输入设备读取数据,将其内容输出到标准输出设备,同时保存成文件。

参数

  • -a 或 --append  附加到既有文件的后面,而非覆盖它。
  • -i 或 --ignore-interrupts  忽略中断信号。
  • --help  在线帮助。
  • --version  显示版本信息。

tee test.txt

使用指令 tee 将用户输入的数据保存到文件 test.txt

[root@master shell_learning]# tee test.txt                        
hello world
hello world
^C
[root@master shell_learning]# cat test.txt
hello world

echo "hello world" | tee  test.txt

将屏幕输出内容写到 test.txt

[root@master shell_learning]# echo "hello world" | tee test.txt  
hello world
[root@master shell_learning]# cat test.txt
hello world

 echo "hello world" | tee -a test.txt

将屏幕输出内容追加到 test.txt

[root@master shell_learning]# echo "hello world" | tee -a test.txt
hello world
[root@master shell_learning]# cat test.txt
hello world
hello world

tmpwatch

执行 tmpwatch 指令可删除不必要的暂存文件,您可以设置文件超期时间,单位以小时计算。

可能需要自己安装:

[root@master ~]# yum -y install tmpwatch

参数

  • -a或--all  删除任何类型的文件。
  • -f或--force  强制删除文件或目录,其效果类似rm指令的"-f"参数。
  • -q或--quiet  不显示指令执行过程。
  • -v或--verbose  详细显示指令执行过程。
  • -test  仅作测试,并不真的删除文件或目录。

tmpwatch 24 /tmp/ 

[root@master tmp]# tmpwatch 24 /tmp/

touch

touch 命令用于修改文件或者目录的时间属性,包括存取时间和更改时间。若文件不存在,系统会建立一个新的文件。ls -l 可以显示档案的时间记录。

参数

  • -a 改变档案的读取时间记录。
  • -m 改变档案的修改时间记录。
  • -c 假如目的档案不存在,不会建立新的档案。与 --no-create 的效果一样。
  • -f 不使用,是为了与其他 unix 系统的相容性而保留。
  • -r 使用参考档的时间记录,与 --file 的效果一样。
  • -d 设定时间与日期,可以使用各种不同的格式。
  • -t 设定档案的时间记录,格式与 date 指令相同。
  • --no-create 不会建立新档案。
  • --help 列出指令格式。
  • --version 列出版本讯息。

 touch file1.txt

[root@master shell_learning]# ll
total 52
-rw-rw-r--. 1 root looking    47 Aug 25 23:06 file1.txt
-rw-rw-r--. 1 root looking    28 Aug 25 23:07 file2.txt
-rw-r--r--. 1 root looking 13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root root      117 Sep 18 22:12 out.txt
-rw-r--r--. 1 root looking    90 Apr  2 14:28 passwd.txt
-rw-r--r--. 1 root root       47 Sep  1 22:24 test.rb
-rw-r--r--. 1 root root       12 Sep 19 23:01 test.txt
-rw-r--r--. 2 root looking    56 Aug 24 22:20 textfile2.txt
-rw-r--r--. 2 root looking    56 Aug 24 22:20 textfile.txt
lrwxrwxrwx. 1 root root       12 Sep 17 23:12 textfile.txt.link -> textfile.txt
-rw-r--r--. 1 root looking   276 Apr 27 14:34 user.txt
[root@master shell_learning]# touch file1.txt
[root@master shell_learning]# ll
total 52
-rw-rw-r--. 1 root looking    47 Sep 23 21:01 file1.txt
-rw-rw-r--. 1 root looking    28 Aug 25 23:07 file2.txt
-rw-r--r--. 1 root looking 13185 Sep 18  2019 get-docker.sh
-rw-r--r--. 1 root root      117 Sep 18 22:12 out.txt
-rw-r--r--. 1 root looking    90 Apr  2 14:28 passwd.txt
-rw-r--r--. 1 root root       47 Sep  1 22:24 test.rb
-rw-r--r--. 1 root root       12 Sep 19 23:01 test.txt
-rw-r--r--. 2 root looking    56 Aug 24 22:20 textfile2.txt
-rw-r--r--. 2 root looking    56 Aug 24 22:20 textfile.txt
lrwxrwxrwx. 1 root root       12 Sep 17 23:12 textfile.txt.link -> textfile.txt
-rw-r--r--. 1 root looking   276 Apr 27 14:34 user.txt

 touch file3.txt 

[root@master shell_learning]# ls
file1.txt  get-docker.sh  passwd.txt  test.txt       textfile.txt       user.txt
file2.txt  out.txt        test.rb     textfile2.txt  textfile.txt.link
[root@master shell_learning]# touch file3.txt
[root@master shell_learning]# ls
file1.txt  file3.txt      out.txt     test.rb   textfile2.txt  textfile.txt.link
file2.txt  get-docker.sh  passwd.txt  test.txt  textfile.txt   user.txt

umask

umask 可用来设定[权限掩码]。[权限掩码]是由 3 个八进制的数字所组成,将现有的存取权限 [777] 减掉权限掩码后,即可产生建立文件时预设的权限。

umask 002

Linux 基础命令学习_第1张图片

root@master ~/w/shell_learning# umask
0022
root@master ~/w/shell_learning# umask -S
u=rwx,g=rx,o=rx
[root@master shell_learning]# ll
drwxr-xr-x. 2 root root        6 Jun 24 14:34 test1_dir
-rw-r--r--. 1 root root        0 Jun 24 14:36 test1_file

[root@master shell_learning]# ll
drwxr-xr-x. 2 root root        6 Jun 24 14:34 test1_dir
-rw-r--r--. 1 root root        0 Jun 24 14:36 test1_file
drwxrwxr-x. 2 root root        6 Jun 24 14:39 test2_dir
-rw-rw-r--. 1 root root        0 Jun 24 14:39 test2_file

which

which 指令会在环境变量 $PATH 设置的目录里查找符合条件的文件。

which bash

[root@master shell_learning]# which bash
/usr/bin/bash
[root@master shell_learning]# which ruby
/usr/bin/ruby
[root@master shell_learning]# which python3
/usr/bin/python3

whereis

whereis 用于查找文件。该指令会在特定目录中查找符合条件的文件。这些文件应属于原始代码、二进制文件,或是帮助文件。

参数

  • -b  只查找二进制文件。
  • -B <目录>  只在设置的目录下查找二进制文件。
  • -f  不显示文件名前的路径名称。
  • -m  只查找说明文件。
  • -M <目录>  只在设置的目录下查找说明文件。
  • -s  只查找原始代码文件。
  • -S <目录>  只在设置的目录下查找原始代码文件。
  • -u  查找不包含指定类型的文件。

whereis bash

[root@master shell_learning]# whereis bash
bash: /usr/bin/bash /usr/share/man/man1/bash.1.gz /usr/share/info/bash.info.gz

[root@master shell_learning]# whereis ruby
ruby: /usr/bin/ruby /usr/lib64/ruby /usr/include/ruby /usr/include/ruby.h /usr/share/ruby /usr/share/man/man1/ruby.1.gz

[root@master shell_learning]# whereis python3
python3: /usr/bin/python3.7m /usr/bin/python3 /usr/bin/python3.7 /usr/lib/python3.7 /usr/lib64/python3.7 /usr/local/lib/python3.7 /usr/include/python3.7m /usr/share/man/man1/python3.1.gz

 whereis -b bash

[root@master shell_learning]# whereis -b bash
bash: /usr/bin/bash

whereis -m bash 

[root@master shell_learning]# whereis -m bash
bash: /usr/share/man/man1/bash.1.gz /usr/share/info/bash.info.gz

read

read 内部命令被用来从标准输入读取单行数据。这个命令可以用来读取键盘输入,当使用重定向的时候,可以读取文件中的一行数据。

参数:

  • -a 后跟一个变量,该变量会被认为是个数组,然后给其赋值,默认是以空格为分割符。
  • -d 后面跟一个标志符,其实只有其后的第一个字符有用,作为结束的标志。
  • -p 后面跟提示信息,即在输入前打印提示信息。
  • -e 在输入的时候可以使用命令补全功能。
  • -n 后跟一个数字,定义输入文本的长度,很实用。
  • -r 屏蔽\,如果没有该选项,则\作为一个转义字符,有的话 \就是个正常的字符了。
  • -s 安静模式,在输入字符时不再屏幕上显示,例如 login 时输入密码。
  • -t 后面跟秒数,定义输入字符的等待时间。
  • -u 后面跟 fd,从文件描述符中读入,该文件描述符可以是 exec 新开启的。

read website

[root@master shell_learning]# cat test.sh
#!/bin/bash

#这里默认会换行  
echo "输入网站名: "  
#读取从键盘的输入  
read website  
echo "你输入的网站名是 $website"  
exit 0  #退出

[root@master shell_learning]# sh test.sh
输入网站名: 
www.runoob.com
你输入的网站名是 www.runoob.com

read -p "some prompt message: " website

-p 参数,允许在 read 命令行中直接指定一个提示。

[root@master shell_learning]# cat test.sh
#!/bin/bash

read -p "输入网站名:" website
echo "你输入的网站名是 $website" 
exit 0

[root@master shell_learning]# sh test.sh
输入网站名:www.runoob.com
你输入的网站名是 www.runoob.com

read -t 5 -p "some prompt message: " website

-t 参数指定 read 命令等待输入的秒数,当计时满时,read命令返回一个非零退出状态。

[root@master shell_learning]# cat test.sh
#!/bin/bash

if read -t 5 -p "输入网站名:" website
then
	echo "你输入的网站名是 $website"
else
	echo -e "\n抱歉,你输入超时了。"
fi
exit 0

[root@master shell_learning]# sh test.sh 
输入网站名:
抱歉,你输入超时了。

[root@master shell_learning]# sh test.sh  
# 输入后记得回车,不然在 5 秒以后还是会显示超时的提示信息!
输入网站名:www.runoob.com
你输入的网站名是 www.runoob.com

read -n1 -p "Do you want to continue [Y/N]?" answer 

-n 参数设置 read 命令计数输入的字符。当输入的字符数目达到预定数目时,自动退出,并将输入的数据赋值给变量。该例子使用了-n 选项,后接数值 1,指示 read 命令只要接受到一个字符就退出。只要按下一个字符进行回答,read 命令立即接受输入并将其传给变量,无需按回车键。

[root@master shell_learning]# cat test.sh
read -n1 -p "Do you want to continue [Y/N]?" answer
case $answer in
	Y | y)
		echo -e "\nfine, continue!";;
	N | n)
		echo -e "\nok, good bye!";;
	*)
		echo -e "\nerror choice!";;
esac
exit 0

[root@master shell_learning]# sh test.sh 
Do you want to continue [Y/N]?y
fine, continue!

[root@master shell_learning]# sh test.sh
Do you want to continue [Y/N]?n
ok, good bye!

[root@master shell_learning]# sh test.sh
Do you want to continue [Y/N]?t
error choice!

 read -n2 -p "type two characters: " any

[root@master shell_learning]# cat test.sh
#!/bin/bash

read -n2 -p "请随便输入两个字符: " any
echo -e "\n您输入的两个字符是:$any"
exit 0

[root@master shell_learning]# sh test.sh 
请随便输入两个字符: lo
您输入的两个字符是:lo

read -s -p "type your password: " password 

[root@master shell_learning]# cat test.sh
#!/bin/bash

read  -s  -p "请输入您的密码:" password
echo -e "\n您输入的密码是 $password"
exit 0

[root@master shell_learning]# sh test.sh
请输入您的密码:
您输入的密码是 Looking

读取文件

每次调用 read 命令都会读取文件中的 "一行" 文本。当文件没有可读的行时,read 命令将以非零状态退出。通过什么样的方法将文件中的数据传给 read 呢?使用 cat 命令并通过管道将结果直接传送给包含 read 命令的 while 命令。

[root@master shell_learning]# cat test.txt
^orld world
No 2 number

[root@master shell_learning]# cat test.sh
#!/bin/bash
  
count=1    # 赋值语句,不加空格
cat test.txt | while read line # cat 命令的输出作为read命令的输入, read读到 > 的值放在line中
do
	echo "Line $count:$line"
	count=$[ $count + 1 ]      # 注意中括号中的空格。
done
echo "finished"
exit 0

[root@master shell_learning]# sh test.sh
Line 1:^orld world
Line 2:No 2 number
finished

read -e -p "type filename: " str 

使用 -e 参数,以下实例输入字符 a 后按下 Tab 键就会输出相关的文件名(该目录存在的) 。

[root@master shell_learning]# cat test.sh
read -e -p "输入文件名:" str 

[root@master shell_learning]# sh test.sh
输入文件名:t
testfile      test.sh       test.txt      textfile.txt  ttt.txt       
输入文件名:test
testfile  test.sh   test.txt  
输入文件名:test.txt

文档编辑

colrm

colrm 指令从标准输入设备读取数据,转而输出到标准输出设备。如果不加任何参数,则该指令不会过滤任何一行。

参数:

  • 开始行数编号: 指定要删除的列的起始编号。
  • 结束行数编号: 指定要删除的列的结束编号,有时候这个参数可以省略。

colrm

不带任何参数时该命令不会删除任何列

[root@master shell_learning]# colrm
Hello Linux!
Hello Linux!
Hello World
Hello World

colrm 4

如想要删除第4 列之后的所有内容

[root@master shell_learning]# colrm 4
Hello Linux!
Hel

colrm 4 6 

删除第4列到第6列的内容

[root@master shell_learning]# colrm 4 6
Hello Linux!
HelLinux!

comm

comm 命令用于比较两个已排过序的文件。这项指令会一列列地比较两个已排序文件的差异,并将其结果显示出来,如果没有指定任何参数,则会把结果分成 3 列显示:第 1 列仅是在第 1 个文件中出现过的列,第 2 列是仅在第 2 个文件中出现过的列,第 3 列则是在第 1 与第 2 个文件里都出现过的列。若给予的文件名称为 - ,则 comm 指令会从标准输入设备读取数据。

参数

  • -1 不显示只在第 1 个文件里出现过的列。
  • -2 不显示只在第 2 个文件里出现过的列。
  • -3 不显示只在第 1 和第 2 个文件里出现过的列。
  • --help 在线帮助。
  • --version 显示版本信息。

comm file1 file2

[root@master shell_learning]# cat file1
df
dfd
world

[root@master shell_learning]# cat file2
df
dfd
hello

[root@master shell_learning]# comm file1 file2
		        df
		        dfd
	    hello
world

# 如果未排好序,比较会报错
[root@master shell_learning]# cat file1
df
dfd
world

[root@master shell_learning]# cat file2
df
hello
dfd

[root@master shell_learning]# comm file1 file2
		        df
dfd
	    hello
comm: file 2 is not in sorted order
	    dfd
world
comm: input is not in sorted order

comm -1 file1 file2

-1 参数简单理解你可以认为是在 comm file1 file2 结果的基础上减掉了第一列。-2、-3 参数同理。 

[root@master shell_learning]# comm file1 file2   
		        df
		        dfd
	    hello
world

[root@master shell_learning]# comm -1 file1 file2
	    df
	    dfd
hello

csplit

之前学过 split 命令,其用于将一个文件按照指定每多少行分割成数个较小的文件。csplit 命令也用于分割文件,将文件依照指定的范本样式予以切割后,分别保存成名称为 xx00,xx01,xx02... 的文件。若给予的文件名称为 "-",则 csplit 指令会从标准输入设备读取数据。

参数

  • -b <输出格式>或--suffix-format=<输出格式> 预设的输出格式其文件名称为xx00,xx01...等,您可以通过改变<输出格式>来改变输出的文件名。
  • -f <输出字首字符串>或--prefix=<输出字首字符串> 预设的输出字首字符串其文件名为xx00,xx01...等,如果你指定输出字首字符串为"hello",则输出的文件名称会变成hello00,hello01...等。
  • -k 或--keep-files 保留文件,就算发生错误或中断执行,也不能删除已经输出保存的文件。
  • -n <输出文件名位数>或--digits=<输出文件名位数> 预设的输出文件名位数其文件名称为xx00,xx01...等,如果你指定输出文件名位数为"3",则输出的文件名称会变成xx000,xx001...等。
  • -q 或-s或--quiet或--silent 不显示指令执行过程。
  • -z 或--elide-empty-files 删除长度为 0 Byte文件。
  • --help 在线帮助。
  • --version 显示版本信息。

csplit log.txt 2

[root@master shell_learning]# cat log.txt
2 this is a test
3 Are you like awk
This's a test
10 There are orange,apple,mongo

[root@master shell_learning]# csplit log.txt 2
17
65

[root@master shell_learning]# ls
cal.awk  file1  file2  in.txt  logs  log.txt  score.txt  test.sh  test.txt  ttt.txt  xx00  xx01

[root@master shell_learning]# cat xx00
2 this is a test

[root@master shell_learning]# cat xx01
3 Are you like awk
This's a test
10 There are orange,apple,mongo

egrep

egrep 命令用于在文件内查找指定的字符串。执行效果与 "grep-E" 相似,使用的语法及参数可参照 grep 指令,与 grep 的不同点在于解读字符串的方法。egrep 是用 extended regular expression 语法来解读的,而 grep 则用 basic regular expression 语法解读,相比而言,extended regular expression 比 basic regular expression 的表达更强大而且更规范。

更多详情,请参考:Linux 三剑客 grep、sed 和 awk_TomorrowAndTuture的博客-CSDN博客。

扩展表达式:

  • + 匹配一个或者多个先前的字符, 至少一个先前字符。
  • ? 匹配 0 个或者多个先前字符。
  • a|b|c 匹配 a 或 b 或 c。
  • () 字符组, 如: love(able|ers) 匹配 loveable 或 lovers。
  • (..)(..)\1\2 模板匹配. \1代表前面第一个模板, \2代第二个括弧里面的模板。
  • x{m,n} =x\{m,n\} x的字符数量在 m 到 n 个之间。

例子:

egrep '^+' file                以一个或者多个空格开头的行.
grep '^*' file                 同上
egrep '(TOM|DAN) SAVAGE' file  包含 TOM SAVAGE 和DAN SAVAGE的行.
egrep '(ab)+' file             包含至少一个ab的行.
egrep 'x[0-9]?' file           包含x或者x后面跟着0个或者多个数字的行.
egrep 'fun\.$' *               所有文件里面以fun.结尾的行.
egrep '[A-Z]+' file            至少包含一个大写字母的行.
egrep '[0-9]' file             至少一个数字的行.
egrep '[A-Z]...[0-9]' file     有五个字符, 第一个式大写, 最后一个是数字的行.
egrep '[tT]est' file           包含单词test或Test的行.
egrep 'ken sun' file           包含ken sun的行.
egrep -v 'marry' file          不包含marry的行.
egrep -i 'sam' file            不考虑sam的大小写,含有sam的行.
egrep -l "dear ken" *          包含dear ken的所有文件的清单.
egrep -n tom file              包含tom的行, 每行前面追加行号.
egrep -s "$name" file          找到变量名$name的, 不打印而是显示退出状态. 0表示找到. 1表示表达式没找到符合要求的, 2表示文件没找到.

expr

expr 命令是一个手工命令行计数器,用于在 Unix/Linux 下求表达式变量的值,一般用于整数值,也可用于字符串。

表达式说明:

  • 用空格隔开每个项。
  • 用反斜杠 \ 放在 shell 特定的字符前面。
  • 对包含空格和其他特殊字符的字符串要用引号括起来。

expr length "this is a test"

[root@master shell_learning]# expr length "this is a test"
14

expr substr "this is a test" 3 5 

[root@master shell_learning]# expr substr "this is a test" 3 5
is is

expr index "Looking" oo 

[root@master shell_learning]# expr index "Looking" oo
2

 整数运算

[root@master shell_learning]# expr 14 % 9
5

[root@master shell_learning]# expr 14 + 9
23

[root@master shell_learning]# expr 14 / 3    
4

[root@master shell_learning]# expr 14 * 9
expr: syntax error: unexpected argument ‘15104.json’

[root@master shell_learning]# expr 14 \* 9
126

fgrep

grep 指令加上参数 -F,属于固化表达式的搜索,fgrep 命令用于查找文件里符合条件的字符串。

fgrep "^orl" test.txt 

[root@master shell_learning]# cat test.txt
^orld world
No 2 number

[root@master shell_learning]# fgrep "^orl" test.txt 
^orld world

[root@master shell_learning]# grep "\^orl" test.txt
^orld world

fmt

fmt 命令用于编排文本文件。会从指定的文件里读取内容,将其依照指定格式重新编排后,输出到标准输出设备。若指定的文件名为"-",则 fmt 指令会从标准输入设备读取数据。当然,如果运用不得当的话,可能会越排越乱。

参数

  • -c或--crown-margin 每段前两列缩排。
  • -p<列起始字符串>或-prefix=<列起始字符串> 仅合并含有指定字符串的列,通常运用在程序语言的注解方面。
  • -s或--split-only 只拆开字数超出每列字符数的列,但不合并字数不足每列字符数的列。
  • -t或--tagged-paragraph 每列前两列缩排,但第1列和第2列的缩排格式不同。
  • -u或--uniform-spacing 每个字符之间都以一个空格字符间隔,每个句子之间则两个空格字符分隔。
  • -w<每列字符数>或--width=<每列字符数>或-<每列字符数> 设置每列的最大字符数。
  • --help 在线帮助。
  • --version 显示版本信息。

fmt -w 50 log.txt

[root@master shell_learning]# cat log.txt
2 this is a test
3 Are you like awk
This's a test
10 There are orange,apple,mongo

[root@master shell_learning]# fmt log.txt
2 this is a test 3 Are you like awk This's a test 10 There are
orange,apple,mongo

[root@master shell_learning]# fmt -w 50 log.txt
2 this is a test 3 Are you like awk This's a
test 10 There are orange,apple,mongo

fold

fold 命令用于限制文件列宽。fold 指令会从指定的文件里读取内容,将超过限定列宽的列加入增列字符后,输出到标准输出设备。若不指定任何文件名称,或是所给予的文件名为"-",则 fold 指令会从标准输入设备读取数据。

参数

  • -b或--bytes 以Byte为单位计算列宽,而非采用行数编号为单位。
  • -s或--spaces 以空格字符作为换列点。
  • -w<每列行数>或--width<每列行数> 设置每列的最大行数。
  • --help 在线帮助。
  • --version 显示版本信息。

fold -w 10 log.txt

fold -w 10 log.txt 和   fmt -w 10 log.txt 还比较像,但是还有区别的。如果上一行末尾字符不够,fold 不会将下一行的数据补齐到上一行,但是 fmt 会:

[root@master shell_learning]# cat log.txt
2 this is a test
3 Are you like awk
This's a test
10 There are orange,apple,mongo

[root@master shell_learning]# fold -w 10 log.txt
2 this is 
a test
3 Are you 
like awk
This's a t
est
10 There a
re orange,
apple,mong
o

[root@master shell_learning]# fmt -w 10 log.txt
2 this is
a test 3
Are you
like awk
This's a
test 10
There are
orange,apple,mongo

grep

grep 指令用于查找内容包含指定的范本样式的文件,如果发现某文件的内容符合所指定的范本样式,预设 grep 指令会把含有范本样式的那一列显示出来。若不指定任何文件名称,或是所给予的文件名为 -,则 grep 指令会从标准输入设备读取数据。

更多详情,请参考:Linux 三剑客 grep、sed 和 awk_TomorrowAndTuture的博客-CSDN博客。

例子:

grep '\' file        包含单词Tom的行
grep 'Tom savage' file     包含Tom savage的行
grep '^Tommy' file         包含以Tommy开头的行
grep '\.bak$' file         包含以.bak结束的行
grep '[Pp]yramid' file     包含pyramid 或Pyramid的单词的行
grep '[A-Z]' file          包含至少一个大写字母的行
grep '[0-9]' file          包含至少一个数字的行
grep '[A-Z]...[0-9]' file  包含五个字符,以大写开头, 和一个数字结尾的行.
grep -w '[tT]est' file     包含单词和test的行.
grep -s 'ken sun' file     找到包含ken sun的行, 但不打印行, 而是用来检查退出状态.
grep -v aaa file           打印不包含aaa的行.
grep -i cathy file         打印所有包含cathy的行, 而不考虑大小些.
grep -l 'dear cathy' *     打印包含dear cathy的文件的文件名清单.
grep -n tom file           打印匹配的行并追加行号.
grep "$LOGNAME" file       包含变量内容的行, 注意必须用双引号, 单引号则无法引用变量.
grep '$name' file          打印包含字符$name的行.

join

join 命令用于将两个文件中,指定栏位内容相同的行连接起来。找出两个文件中,指定栏位内容相同的行,并加以合并,再输出到标准输出设备。

参数

  • -a<1或2> 除了显示原来的输出内容之外,还显示指令文件中没有相同栏位的行。
  • -e<字符串> 若[文件1]与[文件2]中找不到指定的栏位,则在输出中填入选项中的字符串。
  • -i或--igore-case 比较栏位内容时,忽略大小写的差异。
  • -o<格式> 按照指定的格式来显示结果。
  • -t<字符> 使用栏位的分隔字符。
  • -v<1或2> 跟-a相同,但是只显示文件中没有相同栏位的行。
  • -1<栏位> 连接[文件1]指定的栏位。
  • -2<栏位> 连接[文件2]指定的栏位。
  • --help 显示帮助。
  • --version 显示版本信息。

join file1 file2

join 用起来和 paste 命令有点像,不过还是有区别,你如果用过 MySQL 的 join 的话,就比较好理解了:

[root@master shell_learning]# cat file1
line1 hello
line2 world
line3 nice

[root@master shell_learning]# cat file2
line1 df
line2 dfd
line4 hello

[root@master shell_learning]# paste file1 file2
line1 hello	line1 df
line2 world	line2 dfd
line3 nice	line4 hello

[root@master shell_learning]# join file1 file2
line1 hello df
line2 world dfd

join -a 1 file1 file2

这个其实有点类似于数据库的左连接和右链接啦!

[root@master shell_learning]# cat file1
line1 hello
line2 world
line3 nice

[root@master shell_learning]# cat file2
line1 df
line2 dfd
line4 hello

[root@master shell_learning]# join -a 1 file1 file2
line1 hello df
line2 world dfd
line3 nice

[root@master shell_learning]# join -a 2 file1 file2
line1 hello df
line2 world dfd
line4 hello

let

let 命令是 BASH 中用于计算的工具,用于执行一个或多个表达式,变量计算中不需要加上 $ 来表示变量。如果表达式中包含了空格或其他特殊字符,则必须引起来。

let a=5+4 

[root@master shell_learning]# a=5+4  
[root@master shell_learning]# echo $a
5+4

[root@master shell_learning]# let a=5+4
[root@master shell_learning]# echo $a
9

[root@master shell_learning]# let a++
[root@master shell_learning]# echo $a
10

look

look 指令用于英文单字的查询。您仅需给予它欲查询的字首字符串,它会显示所有开头字符串符合该条件的单字。

参数说明

  • -a 使用另一个字典文件web2,该文件也位于/usr/dict目录下。
  • -d 只对比英文字母和数字,其余一慨忽略不予比对。
  • -f 忽略字符大小写差别。
  • -t<字尾字符串> 设置字尾字符串。

look L testfile

[root@master shell_learning]# cat testfile
HELLO LINUX!  
Linux is a free unix-type opterating system.  
This is a linux testfile!  
Linux test

在 testfile 文件中使用 look 命令查找以"L"开头的单词,期望结果如下:

[root@master shell_learning]# look L testfile  #查找以“L”开头的单词  
Linux is a free unix-type opterating system.   #第二行以“L”开头,列出全句  
Linux test                                     #第四行以“L”开头,列出全句 

实际结果却是这样只有一行(不知道是不是这个 look 版本太低的缘故): 

[root@master shell_learning]# look --version
look from util-linux 2.34

[root@master shell_learning]# cat testfile
HELLO LINUX!  
Linux is a free unix-type opterating system.  
This is a linux testfile!  
Linux test
 
[root@master shell_learning]# look L testfile
Linux is a free unix-type opterating system. 

sed

sed 主要用来自动编辑一个或多个文件、简化对文件的反复操作、编写转换程序等。

更多详情,请参考:Linux 三剑客 grep、sed 和 awk_TomorrowAndTuture的博客-CSDN博客。

sort

sort 可针对文本文件的内容,以行为单位来排序。

参数

  • -b 忽略每行前面开始出的空格字符。
  • -c 检查文件是否已经按照顺序排序。
  • -d 排序时,处理英文字母、数字及空格字符外,忽略其他的字符。
  • -f 排序时,将小写字母视为大写字母。
  • -i 排序时,除了040至176之间的ASCII字符外,忽略其他的字符。
  • -m 将几个排序好的文件进行合并。
  • -M 将前面3个字母依照月份的缩写进行排序。
  • -n 依照数值的大小排序。
  • -u 意味着是唯一的(unique),输出的结果是去完重了的。
  • -o<输出文件> 将排序后的结果存入指定的文件。
  • -r 以相反的顺序来排序。
  • -t<分隔字符> 指定排序时所用的栏位分隔字符。
  • +<起始栏位>-<结束栏位> 以指定的栏位来排序,范围由起始栏位到结束栏位的前一栏位。
  • --help 显示帮助。
  • --version 显示版本信息。

sort textfile

sort 命令将以默认的方式将文本文件的第一列以ASCII 码的次序排列,并将结果输出到标准输出。

[root@master shell_learning]# cat textfile.txt
hello
hello
world
hello
nice
great
good
nice
good
[root@master shell_learning]# sort textfile.txt 
good
good
great
hello
hello
hello
nice
nice
world

sort textfile.txt | uniq -c

排序 + 统计

[root@master shell_learning]# sort textfile.txt | uniq -c
      2 good
      1 great
      3 hello
      2 nice
      1 world

sort textfile.txt | uniq -c | sort -nr 

排序 + 统计 + 次数逆序重排

[root@master shell_learning]# sort textfile.txt | uniq -c | sort -nr
      3 hello
      2 nice
      2 good
      1 world
      1 great

sort textfile.txt | uniq -c | sort -nr | head -3

排序 + 统计 + 次数逆序重排  + 取前 3

[root@master shell_learning]# sort textfile.txt | uniq -c | sort -nr | head -3
      3 hello
      2 nice
      2 good

tr

tr 命令用于转换或删除文件中的字符。tr 指令从标准输入设备读取数据,经过字符串转译后,将结果输出到标准输出设备。

参数:

  • -c, --complement:反选设定字符。也就是符合 SET1 的部份不做处理,不符合的剩余部份才进行转换
  • -d, --delete:删除指令字符
  • -s, --squeeze-repeats:缩减连续重复的字符成指定的单个字符
  • -t, --truncate-set1:削减 SET1 指定范围,使之与 SET2 设定长度相等
  • --help:显示程序用法信息
  • --version:显示程序本身的版本信息

字符集合的范围:

  • \NNN 八进制值的字符 NNN (1 to 3 为八进制值的字符)
  • \\ 反斜杠
  • \a Ctrl-G 铃声
  • \b Ctrl-H 退格符
  • \f Ctrl-L 走行换页
  • \n Ctrl-J 新行
  • \r Ctrl-M 回车
  • \t Ctrl-I tab键
  • \v Ctrl-X 水平制表符
  • CHAR1-CHAR2 :字符范围从 CHAR1 到 CHAR2 的指定,范围的指定以 ASCII 码的次序为基础,只能由小到大,不能由大到小。
  • [:alnum:] :所有字母字符与数字
  • [:alpha:] :所有字母字符
  • [:blank:] :所有水平空格
  • [:cntrl:] :所有控制字符
  • [:digit:] :所有数字
  • [:graph:] :所有可打印的字符(不包含空格符)
  • [:lower:] :所有小写字母
  • [:print:] :所有可打印的字符(包含空格符)
  • [:punct:] :所有标点字符
  • [:space:] :所有水平与垂直空格符
  • [:upper:] :所有大写字母
  • [:xdigit:] :所有 16 进位制的数字
  • [=CHAR=] :所有符合指定的字符(等号里的 CHAR,代表你可自订的字符)

cat log.txt | tr a-z A-Z

[root@master shell_learning]# cat log.txt
2 this is a test
3 Are you like awk
This's a test
10 There are orange,apple,mongo

[root@master shell_learning]# cat log.txt | tr a-z A-Z
2 THIS IS A TEST
3 ARE YOU LIKE AWK
THIS'S A TEST
10 THERE ARE ORANGE,APPLE,MONGO

[root@master shell_learning]# cat log.txt | tr [:lower:] [:upper:]
2 THIS IS A TEST
3 ARE YOU LIKE AWK
THIS'S A TEST
10 THERE ARE ORANGE,APPLE,MONGO

uniq

uniq 命令用于检查及删除文本文件中重复出现的行列,一般与 sort 命令结合使用。当重复的行并不相邻时,uniq 命令是不起作用的。

参数

  • -c或--count 在每列旁边显示该行重复出现的次数。
  • -d或--repeated 仅显示重复出现的行列。
  • -f<栏位>或--skip-fields=<栏位> 忽略比较指定的栏位。
  • -s<字符位置>或--skip-chars=<字符位置> 忽略比较指定的字符。
  • -u或--unique 仅显示出一次的行列。
  • -w<字符位置>或--check-chars=<字符位置> 指定要比较的字符。
  • --help 显示帮助。
  • --version 显示版本信息。
  • [输入文件] 指定已排序好的文本文件。如果不指定此项,则从标准读取数据;
  • [输出文件] 指定输出的文件。如果不指定此选项,则将内容显示到标准输出设备(显示终端)。

uniq -c

[root@master shell_learning]# cat textfile.txt 
hello
hello
world
hello
nice
great
good
nice
good

[root@master shell_learning]# uniq textfile.txt
hello
world
hello
nice
great
good
nice
good

[root@master shell_learning]# sort textfile.txt| uniq -c
      2 good
      1 great
      3 hello
      2 nice
      1 world

wc

wc 命令用于计算字数。利用 wc 指令我们可以计算文件的 Byte 数、字数、或是列数,若不指定文件名称、或是所给予的文件名为"-",则 wc 指令会从标准输入设备读取数据。

参数

  • -c或--bytes或--chars 只显示Bytes数。
  • -l或--lines 只显示行数。
  • -w或--words 只显示字数。
  • --help 在线帮助。
  • --version 显示版本信息。

wc log.txt 
3 个数字分别表示文件的行数、单词数,以及该文件的字节数。

[root@master shell_learning]# cat log.txt
2 this is a test
3 Are you like awk
This's a test
10 There are orange,apple,mongo

[root@master shell_learning]# wc log.txt 
行数    词数    字节数    文件名
 4      17      82      log.txt

wc file1 file2 textfile.txt 

同时统计多个文件的信息

[root@master shell_learning]# wc file1 file2 textfile.txt 
  3   6  35 file1
  3   6  31 file2
  9   9  50 textfile.txt
 15  21 116 total

磁盘管理

cd

cd 命令用于切换当前工作目录。其中目录名称表示法可为绝对路径或相对路径。若目录名称省略,则变换至使用者的 home 目录 (也就是刚 login 时所在的目录)。

另外,~ 也表示为 home 目录 的意思, . 则是表示目前所在的目录, .. 则表示目前目录位置的上一层目录。

df

df 命令用于显示目前在 Linux 系统上的文件系统磁盘使用情况统计。

参数

  • -a, --all 包含所有的具有 0 Blocks 的文件系统
  • --block-size={SIZE} 使用 {SIZE} 大小的 Blocks
  • -h, --human-readable 使用人类可读的格式(预设值是不加这个选项的...)
  • -H, --si 很像 -h, 但是用 1000 为单位而不是用 1024
  • -i, --inodes 列出 inode 资讯,不列出已使用 block
  • -k, --kilobytes 就像是 --block-size=1024
  • -l, --local 限制列出的文件结构
  • -m, --megabytes 就像 --block-size=1048576
  • --no-sync 取得资讯前不 sync (预设值)
  • -P, --portability 使用 POSIX 输出格式
  • --sync 在取得资讯前 sync
  • -t, --type=TYPE 限制列出文件系统的 TYPE
  • -T, --print-type 显示文件系统的形式
  • -x, --exclude-type=TYPE 限制列出文件系统不要显示 TYPE
  • -v (忽略)
  • --help 显示这个帮手并且离开
  • --version 输出版本资讯并且离开

df

[root@master shell_learning]# df
Filesystem     1K-blocks    Used     Available Use% Mounted on 
/dev/sda6       29640780 4320704     23814388  16%     / 
udev             1536756       4     1536752    1%     /dev 
tmpfs             617620     888     616732     1%     /run 
none                5120       0     5120       0%     /run/lock 
none             1544044     156     1543888    1%     /run/shm 

df --total 

我们看到输出的末尾,包含一个额外的行,显示总的每一列。

[root@master shell_learning]# df --total
Filesystem     1K-blocks    Used    Available Use% Mounted on 
/dev/sda6       29640780 4320720    23814372  16%     / 
udev             1536756       4    1536752   1%      /dev 
tmpfs             617620     892    616728    1%      /run 
none                5120       0    5120      0%      /run/lock 
none             1544044     156    1543888   1%      /run/shm 
total           33344320 4321772    27516860  14%

 df -h

我们可以看到输出显示的数字形式的'G'(千兆字节),"M"(兆字节)和"K"(千字节)。这使输出容易阅读和理解,从而使显示可读的。请注意,第二列的名称也发生了变化,为了使显示可读的"大小"。

[root@master shell_learning]# df -h
Filesystem      Size  Used   Avail Use% Mounted on 
/dev/sda6       29G   4.2G   23G   16%     / 
udev            1.5G  4.0K   1.5G   1%     /dev 
tmpfs           604M  892K   603M   1%     /run 
none            5.0M     0   5.0M   0%     /run/lock 
none            1.5G  156K   1.5G   1%     /run/shm 

dir

dir 命令用于显示目录记录。

参数

  • +n 显示从左边算起第n笔的目录。
  • -n 显示从右边算起第n笔的目录。
  • -l 显示目录完整的记录。

dir -l

[root@master shell_learning]# dir -l
total 0
drwxr-xr-x. 2 root root 6 Oct  9 23:36 test_dir
-rw-r--r--. 1 root root 0 Oct  9 22:33 test.sh

[root@master shell_learning]# ll
total 0
drwxr-xr-x. 2 root root 6 Oct  9 23:36 test_dir
-rw-r--r--. 1 root root 0 Oct  9 22:33 test.sh

du

du 命令用于显示目录或文件的大小。du 会显示指定的目录或文件所占用的磁盘空间。

参数

  • -a或-all 显示目录中个别文件的大小。
  • -b或-bytes 显示目录或文件大小时,以byte为单位。
  • -c或--total 除了显示个别目录或文件的大小外,同时也显示所有目录或文件的总和。
  • -D或--dereference-args 显示指定符号连接的源文件大小。
  • -h或--human-readable 以K,M,G为单位,提高信息的可读性。
  • -H或--si 与-h参数相同,但是K,M,G是以1000为换算单位。
  • -k或--kilobytes 以1024 bytes为单位。
  • -l或--count-links 重复计算硬件连接的文件。
  • -L<符号连接>或--dereference<符号连接> 显示选项中所指定符号连接的源文件大小。
  • -m或--megabytes 以1MB为单位。
  • -s或--summarize 仅显示总计。
  • -S或--separate-dirs 显示个别目录的大小时,并不含其子目录的大小。
  • -x或--one-file-xystem 以一开始处理时的文件系统为准,若遇上其它不同的文件系统目录则略过。
  • -X<文件>或--exclude-from=<文件> 在<文件>指定目录或文件。
  • --exclude=<目录或文件> 略过指定的目录或文件。
  • --max-depth=<目录层数> 超过指定层数的目录后,予以忽略。
  • --help 显示帮助。
  • --version 显示版本信息。

如果当前目录下各类文件过多,直接 du 的话基本上会一阵刷屏。

du -sh

显示当前目录共占用的空间。

[root@master ~]# pwd
/root
[root@master ~]# du -sh
3.4G	.

du -sh * (常用)

以人可读的方式显示当前目录下各目录和文件所占空间的大小。

[root@master ~]# du -sh *
160K	bisectercise
4.0K	date.sh
32K	deep_learning
1.8M	django_project
4.0K	docker
2.0M	GitTest
84M	looking
2.3G	packages
68M	pycorrector
5.6M	recyclebin
4.0K	render.html
4.0K	test.sh
96K	workspace

du -h workspace

以人方便阅读的格式显示 workspace 目录所占空间情况:

8.0K	workspace/ruby_learning
0	workspace/crystal_learning
8.0K	workspace/python3_learning
36K	workspace/shell_learning
96K	workspace/

ls

ls 命令用于显示指定工作目录下之内容(列出目前工作目录所含之文件及子目录)。

参数 :

  • -a 显示所有文件及目录 (ls内定将文件名或目录名称开头为"."的视为隐藏档,不会列出)
  • -l 除文件名称外,亦将文件型态、权限、拥有者、文件大小等资讯详细列出
  • -r 将文件以相反次序显示(原定依英文字母次序)
  • -t 将文件依建立时间之先后次序列出
  • -d 显示当前目录
  • -A 同 -a ,但不列出 "." (目前目录) 及 ".." (父目录)
  • -F 在列出的文件名称后加一符号;例如可执行档则加 "*", 目录则加 "/"
  • -R 若目录下有文件,则以下之文件亦皆依序列出

ls

[root@master ~]# ls
bisectercise  deep_learning   docker    git      id_rsa.pub  packages     recyclebin   test.sh
date.sh       django_project  first-pr  GitTest  looking     pycorrector  render.html  workspace

ls -AF 

[root@master ~]# ls -AF
.bash_history  .cache/         django_project/  .gemrc      .java/    .m2/            pycorrector/     .tcshrc
.bash_logout   .config/        docker/          git/        .keras/   .mysql_history  .python_history  test.sh*
.bash_profile  .cshrc          .elinks/         .gitconfig  .lesshst  packages/       recyclebin/      .viminfo
.bashrc        date.sh*        first-pr/        GitTest/    .local/   .pip/           render.html      workspace/
bisectercise/  deep_learning/  .gem/            id_rsa.pub  looking/  .pki/           .ssh/

 ls -d GitTest

[root@master ~]# ls GitTest
b.txt  c.txt  hello.txt  looking.txt  myGit.txt  newBranch.txt  readme.txt  test  world.txt
[root@master ~]# ls -d GitTest
GitTest

 ls 2>1

[root@master shell_learning]# ls 2>1
1  file1.txt  file2.txt  get-docker.sh  passwd.txt  test.rb  textfile2.txt  textfile.txt  textfile.txt.link  user.txt

ls xxx 2>1 

[root@master shell_learning]# ls xxx 2>1
[root@master shell_learning]# vim 1

ls: cannot access xxx: No such file or directory

 ls xxx 2>&1

[root@master shell_learning]# ls xxx 2>&1
ls: cannot access xxx: No such file or directory

ls xxx >out.txt 2>&1 

[root@master shell_learning]# ls xxx >out.txt 2>&1
[root@master shell_learning]# vim out.txt

ls: cannot access xxx: No such file or directory

ls >out.txt 2>&1

[root@master shell_learning]# ls >out.txt 2>&1
[root@master shell_learning]# vim out.txt 

1
file1.txt
file2.txt
get-docker.sh
out.txt
passwd.txt
test.rb
textfile2.txt
textfile.txt
textfile.txt.link
user.txt

mkdir

mkdir 命令用于创建目录。

参数

  • -p 确保目录名称存在,不存在的就建一个。
  • -m 设定目录权限。

mkdir test_dir

[root@master shell_learning]# mkdir test_dir
[root@master shell_learning]# ll
total 0
drwxr-xr-x. 2 root root  6 Oct 10 00:21 test_dir
-rw-r--r--. 1 root root  0 Oct  9 22:33 test.sh

mkdir -m 777 test

root@master ~/w/shell_learning# mkdir -m 777 test
root@master ~/w/shell_learning# ll test -d
drwxrwxrwx. 2 root root 6 Jun 23 15:38 test/

mkdir -p test/test_dir 

-p 确保目录上级目录不存在,会主动创建一个。

[root@master shell_learning]# mkdir test/test_dir
mkdir: cannot create directory ‘test/test_dir’: No such file or directory

[root@master shell_learning]# mkdir -p  test/test_dir

[root@master shell_learning]# ll
total 0
drwxr-xr-x. 3 root root 22 Oct 10 00:22 test
drwxr-xr-x. 2 root root  6 Oct 10 00:21 test_dir
-rw-r--r--. 1 root root  0 Oct  9 22:33 test.sh

mount

mount 命令是经常会使用到的命令,它用于挂载 Linux 系统外的文件。mount 准确来说应该是挂载的意思,就是把相应的设备挂载到相关的文件系统下进行访问和控制。比如你插了个 U 盘在 Windows 电脑上,驱动程序识别后给你 U 盘单独分配一个盘符,你就可以像其他系统盘一样去操作你的 U 盘了。

参数:

  • -V:显示程序版本
  • -h:显示辅助讯息
  • -v:显示较讯息,通常和 -f 用来除错。
  • -a:将 /etc/fstab 中定义的所有档案系统挂上。
  • -F:这个命令通常和 -a 一起使用,它会为每一个 mount 的动作产生一个行程负责执行。在系统需要挂上大量 NFS 档案系统时可以加快挂上的动作。
  • -f:通常用在除错的用途。它会使 mount 并不执行实际挂上的动作,而是模拟整个挂上的过程。通常会和 -v 一起使用。
  • -n:一般而言,mount 在挂上后会在 /etc/mtab 中写入一笔资料。但在系统中没有可写入档案系统存在的情况下可以用这个选项取消这个动作。
  • -s-r:等于 -o ro
  • -w:等于 -o rw
  • -L:将含有特定标签的硬盘分割挂上。
  • -U:将档案分割序号为 的档案系统挂下。-L 和 -U 必须在/proc/partition 这种档案存在时才有意义。
  • -t:指定档案系统的型态,通常不必指定。mount 会自动选择正确的型态。
  • -o async:打开非同步模式,所有的档案读写动作都会用非同步模式执行。
  • -o sync:在同步模式下执行。
  • -o atime、-o noatime:当 atime 打开时,系统会在每次读取档案时更新档案的『上一次调用时间』。当我们使用 flash 档案系统时可能会选项把这个选项关闭以减少写入的次数。
  • -o auto、-o noauto:打开/关闭自动挂上模式。
  • -o defaults:使用预设的选项 rw, suid, dev, exec, auto, nouser, and async.
  • -o dev、-o nodev-o exec、-o noexec允许执行档被执行。
  • -o suid、-o nosuid:
  • 允许执行档在 root 权限下执行。
  • -o user、-o nouser:使用者可以执行 mount/umount 的动作。
  • -o remount:将一个已经挂下的档案系统重新用不同的方式挂上。例如原先是唯读的系统,现在用可读写的模式重新挂上。
  • -o ro:用唯读模式挂上。
  • -o rw:用可读写模式挂上。
  • -o loop=:使用 loop 模式用来将一个档案当成硬盘分割挂上系统。
[root@DB-Server tmp]# ls /tmp/rhel-server-5.7-x86_64-dvd.iso
/tmp/rhel-server-5.7-x86_64-dvd.iso
[root@DB-Server tmp]# cd /mnt/
[root@DB-Server mnt]# mkdir cdrom
[root@DB-Server mnt]# mount -o loop /tmp/rhel-server-5.7-x86_64-dvd.iso  /mnt/cdrom/
[root@DB-Server mnt]# cd /mnt/cdrom/

mount /dev/hda1 /mnt

将 /dev/hda1 挂在 /mnt 之下。

[root@master shell_learning]# mount /dev/hda1 /mnt

mount -o ro /dev/hda1 /mnt

将 /dev/hda1 用唯读模式挂在 /mnt 之下。

[root@master shell_learning]# mount -o ro /dev/hda1 /mnt

pwd

pwd 指令可立刻得知您目前所在的工作目录的绝对路径名称。

参数:

  • --help 在线帮助。
  • --version 显示版本信息。

pwd

[root@master shell_learning]# pwd
/root/workspace/shell_learning

rmdir

rmdir 命令删除空的目录。

参数

  • -p 是当子目录被删除后使它也成为空目录的话,则顺便一并删除。

rmdir test

[root@master shell_learning]# ll
total 0
drwxr-xr-x. 3 root root 22 Oct 10 00:22 test
drwxr-xr-x. 2 root root  6 Oct 10 00:21 test_dir
-rw-r--r--. 1 root root  0 Oct  9 22:33 test.sh

[root@master shell_learning]# rmdir test_dir

rmdir -p test/test_dir 

在工作目录下的 test 目录中,删除名为 test_dir 的子目录。若 test_dir 删除后,test 目录成为空目录,则 test 也进行删除。

[root@master shell_learning]# rmdir test
rmdir: failed to remove ‘test’: Directory not empty

[root@master shell_learning]# rmdir -p test
rmdir: failed to remove ‘test’: Directory not empty

[root@master shell_learning]# rmdir -p test/test_dir
[root@master shell_learning]# ll
total 0
-rw-r--r--. 1 root root 0 Oct  9 22:33 test.sh

stat

stat 以文字的格式来显示 inode 的内容。和 Ruby 的 File::stat 有点差不多。

[root@master shell_learning]# stat test.sh
  File: ‘test.sh’
  Size: 0         	Blocks: 0          IO Block: 4096   regular empty file
Device: fd00h/64768d	Inode: 17700393    Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Context: unconfined_u:object_r:admin_home_t:s0
Access: 2020-10-09 22:33:04.040001470 +0800
Modify: 2020-10-09 22:33:01.454001446 +0800
Change: 2020-10-09 22:33:01.454001446 +0800
 Birth: -
irb(main):003:0> require 'pp'
=> true
irb(main):004:0> pp File::stat "test.sh"
#
=> #
irb(main):005:0> 

tree

tree 命令用于以树状图列出目录的内容。执行 tree 指令,它会列出指定目录下的所有文件,包括子目录里的文件。

参数

  • -a 显示所有文件和目录。
  • -A 使用ASNI绘图字符显示树状图而非以ASCII字符组合。
  • -C 在文件和目录清单加上色彩,便于区分各种类型。
  • -d 显示目录名称而非内容。
  • -D 列出文件或目录的更改时间。
  • -f 在每个文件或目录之前,显示完整的相对路径名称。
  • -F 在执行文件,目录,Socket,符号连接,管道名称名称,各自加上"*","/","=","@","|"号。
  • -g 列出文件或目录的所属群组名称,没有对应的名称时,则显示群组识别码。
  • -i 不以阶梯状列出文件或目录名称。
  • -L level 限制目录显示层级(指定树深度)。
  • -l 如遇到性质为符号连接的目录,直接列出该连接所指向的原始目录。
  • -n 不在文件和目录清单加上色彩。
  • -N 直接列出文件和目录名称,包括控制字符。
  • -p 列出权限标示。
  • -P<范本样式> 只显示符合范本样式的文件或目录名称。
  • -q 用"?"号取代控制字符,列出文件和目录名称。
  • -s 列出文件或目录大小。
  • -t 用文件和目录的更改时间排序。
  • -u 列出文件或目录的拥有者名称,没有对应的名称时,则显示用户识别码。
  • -x 将范围局限在现行的文件系统中,若指定目录下的某些子目录,其存放于另一个文件系统上,则将该子目录予以排除在寻找范围外。
  • --prune 忽略空目录

tree

[root@master python3_learning]# tree test3
test3
├── conf.ini
├── foo.txt
├── test4
└── test.py

1 directory, 3 files
[root@master python3_learning]# tree test3 --prune
test3
├── conf.ini
├── foo.txt
└── test.py

0 directories, 3 files

umount

umount 可卸除目前挂在 Linux 目录中的文件系统。

参数

  • -a 卸除/etc/mtab中记录的所有文件系统。
  • -h 显示帮助。
  • -n 卸除时不要将信息存入/etc/mtab文件中。
  • -r 若无法成功卸除,则尝试以只读的方式重新挂入文件系统。
  • -t<文件系统类型> 仅卸除选项中所指定的文件系统。
  • -v 执行时显示详细的信息。
  • -V 显示版本信息。
  • [文件系统] 除了直接指定文件系统外,也可以用设备名称或挂入点来表示文件系统。

umount -v /dev/sda1

下面两条命令分别通过设备名和挂载点卸载文件系统,同时输出详细信息:

[root@master shell_learning]# umount -v /dev/sda1       # 通过设备名卸载  
/dev/sda1 umounted  

[root@master shell_learning]# umount -v /mnt/mymount/   # 通过挂载点卸载  
/tmp/diskboot.img umounted

 umount -v /mnt/mymount/ 

如果设备正忙,卸载即告失败。卸载失败的常见原因是,某个打开的 shell 当前目录为挂载点里的某个目录:

[root@master shell_learning]# umount -v /mnt/mymount/  
umount: /mnt/mymount: device is busy  
umount: /mnt/mymount: device is busy 

磁盘维护

badblocks

badblocks 命令用于检查磁盘装置中损坏的区块。

参数

  • -b<区块大小> 指定磁盘的区块大小,单位为字节。
  • -o<输出文件> 将检查的结果写入指定的输出文件。
  • -s 在检查时显示进度。
  • -v 执行时显示详细的信息。
  • -w 在检查时,执行写入测试。
  • [磁盘装置] 指定要检查的磁盘装置。
  • [磁盘区块数] 指定磁盘装置的区块总数。
  • [启始区块] 指定要从哪个区块开始检查。

badblocks -sv /dev/sda1

[root@master shell_learning]# badblocks -sv /dev/sda1
Checking blocks 0 to 1048575
Checking for bad blocks (read-only test): done                                                 
Pass completed, 0 bad blocks found. (0/0/0 errors)

cfdisk

cfdisk 命令用于磁盘分区。

参数:

  • -a 在程序里不用反白代表选取,而以箭头表示。
  • -c<柱面数目> 忽略BIOS的数值,直接指定磁盘的柱面数目。
  • -h<磁头数目> 忽略BIOS的数值,直接指定磁盘的磁头数目。
  • -P 显示分区表的内容,附加参数"r"会显示整个分区表的详细资料,附加参数"s"会依照磁区的顺序显示相关信息,附加参数"t"则会以磁头,磁区,柱面的方式来显示资料。
  • -s<磁区数目> 忽略BIOS的数值,直接指定磁盘的磁区数目。
  • -v 显示版本信息。
  • -z 不读取现有的分区,直接当作没有分区的新磁盘使用。

cfdisk

[root@master shell_learning]# cfdisk

                                              cfdisk (util-linux 2.23.2)

                                                 Disk Drive: /dev/sda
                                           Size: 32212254720 bytes, 32.2 GB
                                 Heads: 255   Sectors per Track: 63   Cylinders: 3916

     Name              Flags            Part Type	FS Type                  [Label]               Size (MB)
 ---------------------------------------------------------------------------------------------------------------------
                                         Pri/Log        Free Space                                          1.05      *
     sda1              Boot              Primary        xfs                                              1073.75      *
     sda2                                Primary        LVM2_member                                     31137.47      *










       [   Help   ]  [   New    ]  [  Print   ]  [   Quit   ]  [  Units   ]  [  Write   ]


                                         Create new partition from free space

fdisk

fdisk 是一个创建和维护分区表的程序,它兼容DOS类型的分区表、BSD或者SUN类型的磁盘列表。 

必要参数:

  • -l 列出素所有分区表
  • -u 与"-l"搭配使用,显示分区数目

选择参数:

  • -s<分区编号> 指定分区
  • -v 版本信息

菜单操作说明

  • m :显示菜单和帮助信息
  • a :活动分区标记/引导分区
  • d :删除分区
  • l :显示分区类型
  • n :新建分区
  • p :显示分区信息
  • q :退出不保存
  • t :设置分区号
  • v :进行分区检查
  • w :保存修改
  • x :扩展应用,高级功能

fdisk -l

[root@master shell_learning]# fdisk -l

Disk /dev/sda: 32.2 GB, 32212254720 bytes, 62914560 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x000aa951

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     2099199     1048576   83  Linux
/dev/sda2         2099200    62914559    30407680   8e  Linux LVM

Disk /dev/mapper/centos-root: 29.0 GB, 28982640640 bytes, 56606720 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes


Disk /dev/mapper/centos-swap: 2147 MB, 2147483648 bytes, 4194304 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

fdisk -lu 

[root@master shell_learning]# fdisk -lu

Disk /dev/sda: 32.2 GB, 32212254720 bytes, 62914560 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x000aa951

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     2099199     1048576   83  Linux
/dev/sda2         2099200    62914559    30407680   8e  Linux LVM

Disk /dev/mapper/centos-root: 29.0 GB, 28982640640 bytes, 56606720 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes


Disk /dev/mapper/centos-swap: 2147 MB, 2147483648 bytes, 4194304 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

sync

sync 命令用于数据同步,sync命令是在关闭 Linux 系统时使用的。Linux 系统中欲写入硬盘的资料有的时候为了效率起见,会写到 filesystem buffer 中,这个 buffer 是一块记忆体空间,如果欲写入硬盘的资料存于此 buffer 中,而系统又突然断电的话,那么资料就会流失了,sync 指令会将存于 buffer 中的资料强制写入硬盘中。

sync

[root@master shell_learning]# sync

rsync

​​​​​​​rsync 用法教程 - 阮一峰的网络日志 (ruanyifeng.com) 

网络通讯

arpwatch

arpwatch命令用于监听网络上 ARP 的记录。ARP(Address Resolution Protocol) 是用来解析 IP 与网络装置硬件地址的协议。

arpwatch 可监听区域网络中的ARP数据包并记录,同时将监听到的变化通过 E-mail来 报告。

参数

  • -d 启动排错模式。
  • -f<记录文件> 设置存储ARP记录的文件,预设为/var/arpwatch/arp.dat。
  • -i<接口> 指定监听ARP的接口,预设的接口为eth0。
  • -r<记录文件> 从指定的文件中读取ARP记录,而不是从网络上监听。
  • -n 指定附加的本地网络
  • -u 指定用户和用户组
  • -e 发送邮件给指定用户,非默认的root用户
  • -s 指定用户名作为返回地址,而不是默认的用户root

arpwatch -i ens33

[root@master shell_learning]# yum install arpwatch
[root@master shell_learning]# arpwatch -i ens33

From [email protected]  Sat Oct 10 19:43:38 2020
Return-Path: 
X-Original-To: root
Delivered-To: [email protected]
Received: by master.localdomain (Postfix, from userid 0)
        id 3612E202A6ED; Sat, 10 Oct 2020 19:43:38 +0800 (CST)
From: [email protected] (Arpwatch)
To: [email protected]
Subject: new station (master)
Message-Id: <[email protected]>
Date: Sat, 10 Oct 2020 19:43:38 +0800 (CST)

            hostname: master
          ip address: 192.168.128.130
    ethernet address: 00:0c:29:c0:25:3a
     ethernet vendor: VMware, Inc.
           timestamp: Saturday, October 10, 2020 19:43:38 +0800

                         ...

ifconfig

ifconfig 命令用于显示或设置网络设备。可设置网络设备的状态,或是显示目前的设置。

参数

  • add<地址> 设置网络设备IPv6的IP地址。
  • del<地址> 删除网络设备IPv6的IP地址。
  • down 关闭指定的网络设备。
  • <硬件地址> 设置网络设备的类型与硬件地址。
  • io_addr 设置网络设备的I/O地址。
  • irq 设置网络设备的IRQ。
  • media<网络媒介类型> 设置网络设备的媒介类型。
  • mem_start<内存地址> 设置网络设备在主内存所占用的起始地址。
  • metric<数目> 指定在计算数据包的转送次数时,所要加上的数目。
  • mtu<字节> 设置网络设备的MTU。
  • netmask<子网掩码> 设置网络设备的子网掩码。
  • tunnel<地址> 建立IPv4与IPv6之间的隧道通信地址。
  • up 启动指定的网络设备。
  • -broadcast<地址> 将要送往指定地址的数据包当成广播数据包来处理。
  • -pointopoint<地址> 与指定地址的网络设备建立直接连线,此模式具有保密功能。
  • -promisc 关闭或启动指定网络设备的promiscuous模式。
  • [IP地址] 指定网络设备的IP地址。
  • [网络设备] 指定网络设备的名称。

 ifconfig

[root@master shell_learning]# ifconfig
ens33: flags=4163  mtu 1500
        inet 192.168.128.130  netmask 255.255.255.0  broadcast 192.168.128.255
        inet6 fe80::20c:29ff:fec0:253a  prefixlen 64  scopeid 0x20
        ether 00:0c:29:c0:25:3a  txqueuelen 1000  (Ethernet)
        RX packets 1794  bytes 509313 (497.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1030  bytes 126900 (123.9 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 6  bytes 304 (304.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 6  bytes 304 (304.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

mesg

mesg 命令用于设置终端机的写入权限。

将 mesg 设置 y 时,其他用户可利用 write 指令将信息直接显示在您的屏幕上。

参数

  • n 不允许其他用户将信息直接显示在你的屏幕上。
  • y 允许其他用户将信息直接显示在你的屏幕上。

mesg

[root@master shell_learning]# mesg
is y
[root@master shell_learning]# mesg n
[root@master shell_learning]# mesg
is n

netstat

netstat 命令用于显示网络状态。利用 netstat 指令可让你得知整个 Linux 系统的网络情况。

参数

  • -a或--all 显示所有连线中的Socket。
  • -A<网络类型>或--<网络类型> 列出该网络类型连线中的相关地址。
  • -c或--continuous 持续列出网络状态。
  • -C或--cache 显示路由器配置的快取信息。
  • -e或--extend 显示网络其他相关信息。
  • -F或--fib 显示FIB。
  • -g或--groups 显示多重广播功能群组组员名单。
  • -h或--help 在线帮助。
  • -i或--interfaces 显示网络界面信息表单。
  • -l或--listening 显示监控中的服务器的Socket。
  • -M或--masquerade 显示伪装的网络连线。
  • -n或--numeric 直接使用IP地址,而不通过域名服务器。
  • -N或--netlink或--symbolic 显示网络硬件外围设备的符号连接名称。
  • -o或--timers 显示计时器。
  • -p或--programs 显示正在使用Socket的程序识别码和程序名称。
  • -r或--route 显示Routing Table。
  • -s或--statistics 显示网络工作信息统计表。
  • -t或--tcp 显示TCP传输协议的连线状况。
  • -u或--udp 显示UDP传输协议的连线状况。
  • -v或--verbose 显示指令执行过程。
  • -V或--version 显示版本信息。
  • -w或--raw 显示RAW传输协议的连线状况。
  • -x或--unix 此参数的效果和指定"-A unix"参数相同。
  • --ip或--inet 此参数的效果和指定"-A inet"参数相同。

netstat -a

显示详细的网络状况

[root@master shell_learning]# netstat -a
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 0.0.0.0:sunrpc          0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN     
tcp        0      0 master:smtp             0.0.0.0:*               LISTEN     
tcp        0     52 master:ssh              192.168.128.1:64892     ESTABLISHED
tcp        0      0 master:ssh              192.168.128.1:64933     ESTABLISHED
tcp        0   1452 master:ssh              192.168.128.1:50279     ESTABLISHED
tcp6       0      0 [::]:sunrpc             [::]:*                  LISTEN     
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN     
tcp6       0      0 master:smtp             [::]:*                  LISTEN     
udp        0      0 0.0.0.0:940             0.0.0.0:*                          
udp        0      0 0.0.0.0:sunrpc          0.0.0.0:*                          
udp6       0      0 [::]:940                [::]:*                             
udp6       0      0 [::]:sunrpc             [::]:*                             
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  3      [ ]         DGRAM                    8991     /run/systemd/notify
unix  2      [ ]         DGRAM                    8993     /run/systemd/cgroups-agent
unix  2      [ ACC ]     STREAM     LISTENING     42344    private/proxywrite
unix  2      [ ACC ]     STREAM     LISTENING     42347    private/smtp
unix  2      [ ACC ]     STREAM     LISTENING     42350    private/relay
unix  2      [ ACC ]     STREAM     LISTENING     42356    private/error
unix  2      [ ACC ]     STREAM     LISTENING     9005     /run/systemd/journal/stdout
unix  2      [ ACC ]     STREAM     LISTENING     42359    private/retry
unix  2      [ ACC ]     STREAM     LISTENING     42362    private/discard
unix  5      [ ]         DGRAM                    9008     /run/systemd/journal/socket
unix  2      [ ACC ]     STREAM     LISTENING     42365    private/local
unix  2      [ ACC ]     STREAM     LISTENING     42368    private/virtual
unix  16     [ ]         DGRAM                    9010     /dev/log
...

netstat -apu

显示UDP端口号的使用情况

[root@master shell_learning]# netstat -apu
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
udp        0      0 0.0.0.0:940             0.0.0.0:*                           6290/rpcbind        
udp        0      0 0.0.0.0:sunrpc          0.0.0.0:*                           6290/rpcbind        
udp6       0      0 [::]:940                [::]:*                              6290/rpcbind        
udp6       0      0 [::]:sunrpc             [::]:*                              6290/rpcbind 

netstat -i

显示网卡列表

[root@master shell_learning]# netstat -i
Kernel Interface table
Iface             MTU    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
ens33            1500     2574      0      0 0          1548      0      0      0 BMRU
lo              65536        6      0      0 0             6      0      0      0 LRU

netstat -g

显示播报组的关系

[root@master shell_learning]# netstat -g
IPv6/IPv4 Group Memberships
Interface       RefCnt Group
--------------- ------ ---------------------
lo              1      all-systems.mcast.net
ens33           1      all-systems.mcast.net
lo              1      ff02::1
lo              1      ff01::1
ens33           1      ff02::1:ffc0:253a
ens33           1      ff02::1
ens33           1      ff01::1

netstat -s

显示网络统计信息

[root@master shell_learning]# netstat -s
Ip:
    2203 total packets received
    0 forwarded
    0 incoming packets discarded
    1884 incoming packets delivered
    1448 requests sent out
Icmp:
    5 ICMP messages received
    0 input ICMP message failed.
    ICMP input histogram:
        destination unreachable: 3
        echo replies: 2
    5 ICMP messages sent
    0 ICMP messages failed
    ICMP output histogram:
        destination unreachable: 3
        echo request: 2
IcmpMsg:
        InType0: 2
        InType3: 3
        OutType3: 3
        OutType8: 2
Tcp:
    23 active connections openings
    4 passive connection openings
    0 failed connection attempts
    1 connection resets received
    2 connections established
    1754 segments received
    1305 segments send out
    18 segments retransmited
    0 bad segments received.
    0 resets sent
Udp:
    122 packets received
    3 packets to unknown port received.
    0 packet receive errors
    125 packets sent
    0 receive buffer errors
    0 send buffer errors
UdpLite:
TcpExt:
    22 TCP sockets finished time wait in fast timer
    56 delayed acks sent
    4 packets directly queued to recvmsg prequeue.
    460 packet headers predicted
    302 acknowledgments not containing data payload received
    504 predicted acknowledgments
    3 other TCP timeouts
    TCPLossProbes: 1
    1 connections aborted due to timeout
    TCPRcvCoalesce: 74
    TCPSynRetrans: 2
    TCPOrigDataSent: 969
IpExt:
    InBcastPkts: 66
    InOctets: 525803
    OutOctets: 182929
    InBcastOctets: 5364
    InNoECTPkts: 2338

netstat -l

显示监听的套接口

[root@master shell_learning]# netstat -l
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 0.0.0.0:sunrpc          0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN     
tcp        0      0 master:smtp             0.0.0.0:*               LISTEN     
tcp6       0      0 [::]:sunrpc             [::]:*                  LISTEN     
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN     
tcp6       0      0 master:smtp             [::]:*                  LISTEN     
udp        0      0 0.0.0.0:940             0.0.0.0:*                          
udp        0      0 0.0.0.0:sunrpc          0.0.0.0:*                          
udp6       0      0 [::]:940                [::]:*                             
udp6       0      0 [::]:sunrpc             [::]:*                             
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     42344    private/proxywrite
unix  2      [ ACC ]     STREAM     LISTENING     42347    private/smtp
unix  2      [ ACC ]     STREAM     LISTENING     42350    private/relay
unix  2      [ ACC ]     STREAM     LISTENING     42356    private/error
unix  2      [ ACC ]     STREAM     LISTENING     9005     /run/systemd/journal/stdout
unix  2      [ ACC ]     STREAM     LISTENING     42359    private/retry
unix  2      [ ACC ]     STREAM     LISTENING     42362    private/discard
unix  2      [ ACC ]     STREAM     LISTENING     42365    private/local
unix  2      [ ACC ]     STREAM     LISTENING     42368    private/virtual
unix  2      [ ACC ]     STREAM     LISTENING     42371    private/lmtp
unix  2      [ ACC ]     STREAM     LISTENING     42374    private/anvil
unix  2      [ ACC ]     STREAM     LISTENING     42377    private/scache
unix  2      [ ACC ]     STREAM     LISTENING     42320    private/tlsmgr
unix  2      [ ACC ]     STREAM     LISTENING     42323    private/rewrite
unix  2      [ ACC ]     STREAM     LISTENING     42332    private/trace
unix  2      [ ACC ]     STREAM     LISTENING     42341    private/proxymap
unix  2      [ ACC ]     STREAM     LISTENING     42335    private/verify
unix  2      [ ACC ]     STREAM     LISTENING     42329    private/defer
unix  2      [ ACC ]     STREAM     LISTENING     21404    /run/systemd/private
unix  2      [ ACC ]     STREAM     LISTENING     33909    /run/dbus/system_bus_socket
unix  2      [ ACC ]     STREAM     LISTENING     21454    /run/lvm/lvmpolld.socket
unix  2      [ ACC ]     STREAM     LISTENING     21463    /run/lvm/lvmetad.socket
unix  2      [ ACC ]     STREAM     LISTENING     34782    /var/run/abrt/abrt.socket
unix  2      [ ACC ]     STREAM     LISTENING     34011    /var/run/pcscd/pcscd.comm
unix  2      [ ACC ]     STREAM     LISTENING     34785    /var/run/vmware/guestServicePipe
unix  2      [ ACC ]     STREAM     LISTENING     42309    public/pickup
unix  2      [ ACC ]     STREAM     LISTENING     42313    public/cleanup
unix  2      [ ACC ]     SEQPACKET  LISTENING     21478    /run/udev/control
unix  2      [ ACC ]     STREAM     LISTENING     42326    private/bounce
unix  2      [ ACC ]     STREAM     LISTENING     42316    public/qmgr
unix  2      [ ACC ]     STREAM     LISTENING     42338    public/flush
unix  2      [ ACC ]     STREAM     LISTENING     42353    public/showq
unix  2      [ ACC ]     STREAM     LISTENING     34026    /var/run/rpcbind.sock

ping

ping 命令用于检测主机。执行 ping 指令会使用 ICMP 传输协议,发出要求回应的信息,若远端主机的网络功能没有问题,就会回应该信息,因而得知该主机运作正常。

参数

  • -d 使用Socket的SO_DEBUG功能。
  • -c<完成次数> 设置完成要求回应的次数。
  • -f 极限检测。
  • -i<间隔秒数> 指定收发信息的间隔时间。
  • -I<网络界面> 使用指定的网络接口送出数据包。
  • -l<前置载入> 设置在送出要求信息之前,先行发出的数据包。
  • -n 只输出数值。
  • -p<范本样式> 设置填满数据包的范本样式。
  • -q 不显示指令执行过程,开头和结尾的相关信息除外。
  • -r 忽略普通的Routing Table,直接将数据包送到远端主机上。
  • -R 记录路由过程。
  • -s<数据包大小> 设置数据包的大小。
  • -t<存活数值> 设置存活数值TTL的大小。
  • -v 详细显示指令的执行过程。

ping www.w3cschool.cc

[root@master shell_learning]# ping www.w3cschool.cc
PING www.w3cschool.cc (203.107.43.165) 56(84) bytes of data.
64 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=1 ttl=128 time=33.6 ms
64 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=2 ttl=128 time=35.0 ms
64 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=3 ttl=128 time=34.0 ms
64 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=4 ttl=128 time=34.2 ms
64 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=5 ttl=128 time=34.2 ms
64 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=6 ttl=128 time=34.4 ms
^C
--- www.w3cschool.cc ping statistics ---
6 packets transmitted, 6 received, 0% packet loss, time 5008ms
rtt min/avg/max/mdev = 33.604/34.282/35.006/0.448 ms

ping -c2 www.w3cschool.cc 

指定接收包的次数

[root@master shell_learning]# ping -c2 www.w3cschool.cc
PING www.w3cschool.cc (203.107.43.165) 56(84) bytes of data.
64 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=1 ttl=128 time=37.7 ms
64 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=2 ttl=128 time=34.2 ms

--- www.w3cschool.cc ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 34.282/36.012/37.743/1.740 ms

 ping -i 3 -s 1024 -t 255 www.w3cschool.cc

[root@master shell_learning]# ping -i 3 -s 1024 -t 255 www.w3cschool.cc
# -i 3 发送周期为 3秒 -s 设置发送包的大小 -t 设置TTL值为 255
PING www.w3cschool.cc (203.107.43.165) 1024(1052) bytes of data.
1032 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=1 ttl=128 time=33.2 ms
1032 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=2 ttl=128 time=36.9 ms
1032 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=3 ttl=128 time=34.7 ms
1032 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=4 ttl=128 time=34.0 ms
1032 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=5 ttl=128 time=33.0 ms
1032 bytes from 203.107.43.165 (203.107.43.165): icmp_seq=6 ttl=128 time=34.4 ms
^C
--- www.w3cschool.cc ping statistics ---
6 packets transmitted, 6 received, 0% packet loss, time 15018ms
rtt min/avg/max/mdev = 33.021/34.422/36.996/1.331 ms

tty

tty 命令用于显示终端机连接标准输入设备的文件名称。在 Linux 操作系统中,所有外围设备都有其名称与代号,这些名称代号以特殊文件的类型存放于 /dev 目录下。你可以执行 tty(teletypewriter) 指令查询目前使用的终端机的文件名称。

tty

[root@master shell_learning]# tty
/dev/pts/1

wall

wall 命令会将讯息传给每一个 mesg 设定为 yes 的上线使用者。当使用终端机界面做为标准传入时, 讯息结束时需加上 EOF (通常用 Ctrl+D)。 

wall hello world

[root@master shell_learning]# wall hello world
[root@master shell_learning]# 
Broadcast message from root@master (pts/1) (Sat Oct 10 20:22:48 2020):

hello world

write

write 命令用于传讯息给其他使用者。

参数

  • user : 预备传讯息的使用者帐号
  • ttyname : 如果使用者同时有两个以上的 tty 连线,可以自行选择合适的 tty 传讯息

write looking

[root@master shell_learning]# write looking
hi, Looking.
I am root
^C
[root@master shell_learning]# 

------------------------------------------------
[looking@master ~]$ 
Message from root@master on pts/1 at 21:11 ...
hi, Looking.
I am root
EOF

系统管理

chfn

chfn 命令提供使用者更改个人资讯,用于 finger and mail username。

chfn

[root@master shell_learning]# chfn
Changing finger information for root.
Name [root]: looking
Office []: anywhere
Office Phone []: 9999999
Home Phone []: 8888888

Finger information changed.

chsh

chsh(change shell)命令用于更改使用者 shell 设定。

chsh 

[looking@master ~]$ chsh
Changing shell for looking.
New shell [/bin/bash]: /bin/sh
Password: 
Shell changed.

chsh -l 

Sorry, user looking may not run sudo on master.
[looking@master ~]$ chsh -l
/bin/sh
/bin/bash
/usr/bin/sh
/usr/bin/bash

exit

exit 命令用于退出目前的 shell。执行 exit 可使 shell 以指定的状态值退出。若不设置状态值参数,则 shell 以预设值退出。状态值 0 代表执行成功,其他值代表执行失败。exit 也可用在 script,离开正在执行的 script,回到 shell。

exit

[root@master shell_learning]# exit
logout

Connection closed by foreign host.

Disconnected from remote host(root) at 16:31:47.

Type `help' to learn how to use Xshell prompt.
[c:\~]$ 

date

date 命令可以用来显示或设定系统的日期与时间。

参数:

  • -d <字符串>:显示字符串所指的日期与时间,字符串前后必须加上双引号
  • -s <字符串>:根据字符串来设置日期与时间,字符串前后必须加上双引号
  • -u:显示GMT
  • --help:在线帮助
  • --version:显示版本信息

在显示方面,使用者可以设定欲显示的格式,格式设定为一个加号后接数个标记,其中可用的标记列表如下:

时间方面:

  • % : 印出 %
  • %n : 下一行
  • %t : 跳格
  • %H : 小时(00..23)
  • %I : 小时(01..12)
  • %k : 小时(0..23)
  • %l : 小时(1..12)
  • %M : 分钟(00..59)
  • %p : 显示本地 AM 或 PM
  • %r : 直接显示时间 (12 小时制,格式为 hh:mm:ss [AP]M)
  • %s : 从 1970 年 1 月 1 日 00:00:00 UTC 到目前为止的秒数
  • %S : 秒(00..61)
  • %T : 直接显示时间 (24 小时制)
  • %X : 相当于 %H:%M:%S
  • %Z : 显示时区

日期方面:

  • %a : 星期几 (Sun..Sat)
  • %A : 星期几 (Sunday..Saturday)
  • %b : 月份 (Jan..Dec)
  • %B : 月份 (January..December)
  • %c : 直接显示日期与时间
  • %d : 日 (01..31)
  • %D : 直接显示日期 (mm/dd/yy)
  • %h : 同 %b
  • %j : 一年中的第几天 (001..366)
  • %m : 月份 (01..12)
  • %U : 一年中的第几周 (00..53) (以 Sunday 为一周的第一天的情形)
  • %w : 一周中的第几天 (0..6)
  • %W : 一年中的第几周 (00..53) (以 Monday 为一周的第一天的情形)
  • %x : 直接显示日期 (mm/dd/yy)
  • %y : 年份的最后两位数字 (00.99)
  • %Y : 完整年份 (0000..9999)

date

 显示当前时间

# 日期与时间
[root@master shell_learning]# date
Mon Sep 28 10:03:07 CST 2020

# 完整日期与时间
[root@master shell_learning]# date "+%c"    
Mon 28 Sep 2020 10:45:28 AM CST

# 当前日期
[root@master shell_learning]# date "+%D"
09/28/20

# 当前完整日期
[root@master shell_learning]# date "+%x"
09/28/2020

# 当前时间
[root@master shell_learning]# date "+%T"
10:45:50

 显示当天日期

[root@master shell_learning]# date +"%Y-%m-%d"
2020-09-28

 显示前一天日期

[root@master shell_learning]# date -d "-1 day" +"%Y-%m-%d"
2020-09-27

 显示后一天日期

[root@master shell_learning]# date -d "+1 day" +"%Y-%m-%d"
2020-09-29

 显示上月日期

[root@master shell_learning]# date -d "-1 month" +"%Y-%m-%d"
2020-08-28

 显示下月日期

[root@master shell_learning]# date -d "+1 month" +"%Y-%m-%d"
2020-10-28

 显示去年日期

[root@master shell_learning]# date -d "-1 year" +"%Y-%m-%d"
2019-09-28

 显示明年日期

[root@master shell_learning]# date -d "+1 year" +"%Y-%m-%d"
2021-09-28

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

格式化显示当前时间 

[root@master shell_learning]# date +"%Y-%m-%d %H:%M:%S" 
2020-09-28 10:07:08

date -d "1 day ago" +"%Y-%m-%d" 

显示昨天日期

[root@master shell_learning]# date -d "1 day ago" +"%Y-%m-%d"
2020-09-27

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

显示 10 秒后的时间

[root@master shell_learning]# date -d "10 second" +"%Y-%m-%d %H:%M.%S"
2020-09-28 10:13.02

date -d "1970-01-01 1234567890 seconds" +"%Y-%m-%d %H:%m:%S"

[root@master shell_learning]# date -d "1970-01-01 1234567890 seconds" +"%Y-%m-%d %H:%m:%S"
2009-02-13 23:02:30

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

普通格式转换

[root@master shell_learning]# date -d "2009-12-12" +"%Y-%m-%d %H:%M.%S"                 
2009-12-12 00:00.00

date -d "Jan 5, 2009 12:00:37 AM" +"%Y-%m-%d %H:%M:%S"

apache 格式转换

[root@master shell_learning]# date -d "10 second" +"%Y-%m-%d %H:%M.%S"
2020-09-28 10:13.02

date -d "Dec 5, 2009 12:00:37 PM 2 year ago" +"%Y-%m-%d %H:%M:%S"

格式转换后时间

[root@master shell_learning]# date -d "Dec 5, 2009 12:00:37 PM 2 year ago" +"%Y-%m-%d %H:%M:%S"
2007-12-05 12:00:37

finger

finger 命令可以让使用者查询一些其他使用者的资料。

参数

  • -l  多行显示。
  • -s  单行显示。这个选项只显示登入名称、真实姓名、终端机名称、闲置时间、登入时间、办公室号码及电话号码。如果所查询的使用者是远端服务器的使用者,这个选项无效。

finger root

[root@master ~]# finger root
Login: root           			Name: looking
Directory: /root                    	Shell: /bin/bash
Office: anywhere, 999-9999		Home Phone: 888-8888
On since Sat Oct 10 22:31 (CST) on pts/1 from 192.168.128.1
   1 second idle
Mail last read Sat Oct 10 19:44 2020 (CST)
No Plan.

finger -l

[root@master ~]# finger -l
Login: looking        			Name: 
Directory: /home/looking            	Shell: /bin/bash
On since Sat Oct 10 22:18 (CST) on pts/0 from 192.168.128.1
   19 minutes 7 seconds idle
No mail.
No Plan.

Login: root           			Name: looking
Directory: /root                    	Shell: /bin/bash
Office: anywhere, 999-9999		Home Phone: 888-8888
On since Sat Oct 10 22:31 (CST) on pts/1 from 192.168.128.1
   7 seconds idle
Mail last read Sat Oct 10 19:44 2020 (CST)
No Plan.

free

free 指令会显示内存的使用情况,包括实体内存,虚拟的交换文件内存,共享内存区段,以及系统核心使用的缓冲区等。

参数

  • -b  以Byte为单位显示内存使用情况。
  • -k  以KB为单位显示内存使用情况。
  • -m  以MB为单位显示内存使用情况。
  • -h  以合适的单位显示内存使用情况,最大为三位数,自动计算对应的单位值。单位有:

    B = bytes
    K = kilos
    M = megas
    G = gigas
    T = teras
  • -o  不显示缓冲区调节列。
  • -s<间隔秒数>  持续观察内存使用状况。
  • -t  显示内存总和列。
  • -V  显示版本信息。

free

显示内存使用情况。

[looking@master ~]$ free
              total        used        free      shared  buff/cache   available
Mem:        1863224      151060     1529140        9844      183024     1523552
Swap:       2097148           0     2097148

Mem 行(第二行)是内存的使用情况。
Swap 行(第三行)是交换空间的使用情况。
total 列显示系统总的可用物理内存和交换空间大小。
used 列显示已经被使用的物理内存和交换空间。
free 列显示还有多少物理内存和交换空间可用使用。
shared 列显示被共享使用的物理内存大小。
buff/cache 列显示被 buffer 和 cache 使用的物理内存大小。
available 列显示还可以被应用程序使用的物理内存大小。 

free 与 available

在 free 命令的输出中,有一个 free 列,同时还有一个 available 列。这二者到底有何区别?
free 是真正尚未被使用的物理内存数量。至于 available 就比较有意思了,它是从应用程序的角度看到的可用内存数量。Linux 内核为了提升磁盘操作的性能,会消耗一部分内存去缓存磁盘数据,就是我们介绍的 buffer 和 cache。所以对于内核来说,buffer 和 cache 都属于已经被使用的内存。当应用程序需要内存时,如果没有足够的 free 内存可以用,内核就会从 buffer 和 cache 中回收内存来满足应用程序的请求。所以从应用程序的角度来说,available  = free + buffer + cache。请注意,这只是一个很理想的计算方式,实际中的数据往往有较大的误差。

free -h 

以适合人阅读的形式显示内存的使用信息。

[looking@master ~]$ free -h
              total        used        free      shared  buff/cache   available
Mem:           1.8G        147M        1.5G        9.6M        178M        1.5G
Swap:          2.0G          0B        2.0G

free -t 

以总和的形式显示内存的使用信息。

[looking@master ~]$ free -t
              total        used        free      shared  buff/cache   available
Mem:        1863224      150660     1529520        9844      183044     1523952
Swap:       2097148           0     2097148
Total:      3960372      150660     3626668

free -s5

周期性的查询内存使用信息。

[looking@master ~]$ free -s5
              total        used        free      shared  buff/cache   available
Mem:        1863224      150660     1529520        9844      183044     1523952
Swap:       2097148           0     2097148

              total        used        free      shared  buff/cache   available
Mem:        1863224      150684     1529496        9844      183044     1523928
Swap:       2097148           0     2097148

groupadd

groupadd 命令用于创建一个新的工作组,新工作组的信息将被添加到系统文件中。

相关文件:

  • /etc/group 组账户信息。
  • /etc/gshadow 安全组账户信息。
  • /etc/login.defs Shadow密码套件配置。

参数:

  • -g:指定新建工作组的 id;
  • -r:创建系统工作组,系统工作组的组ID小于 500;
  • -K:覆盖配置文件 "/ect/login.defs";
  • -o:允许添加组 ID 号不唯一的工作组。
  • -f,--force: 如果指定的组已经存在,此选项将失明了仅以成功状态退出。当与 -g 一起使用,并且指定的GID_MIN已经存在时,选择另一个唯一的GID(即-g关闭)。

groupadd -g 344 runoob 

[root@master ~]# tail -n1 /etc/group
linux:x:1001:

[root@master ~]# groupadd -g 344 runoob

[root@master ~]# tail -n1 /etc/group
runoob:x:344:

groupdel

groupdel 命令用于删除群组。需要从系统上删除群组时,可用 groupdel (group delete) 指令来完成这项工作。倘若该群组中仍包括某些用户,则必须先删除这些用户后,方能删除群组。

groupmod

groupmod 命令用于更改群组识别码或名称。需要更改群组的识别码或名称时,可用 groupmod 指令来完成这项工作。

参数

  • -g <群组识别码>  设置欲使用的群组识别码。
  • -o  重复使用群组识别码。
  • -n <新群组名称>  设置欲使用的群组名称。

 groupadd linuxso

[root@master ~]# tail -1 /etc/group
ntp:x:38:
[root@master ~]# groupadd linuxso
[root@master ~]# tail -1 /etc/group
linuxso:x:1001:

 groupmod -n linux linuxso

[root@master ~]# groupmod -n linux linuxso
[root@master ~]# tail -1 /etc/group
linux:x:1001:

halt

halt 命令关闭系统,否则以 shutdown 指令(加上 -h 参数)来取代。

参数

  • -n : 在关机前不做将记忆体资料写回硬盘的动作
  • -w : 并不会真的关机,只是把记录写到 /var/log/wtmp 文件里
  • -d : 不把记录写到 /var/log/wtmp 文件里(-n 这个参数包含了 -d) -f : 强迫关机,不呼叫 shutdown 这个指令
  • -i : 在关机之前先把所有网络相关的装置先停止
  • -p : 当关机的时候,顺便做关闭电源(poweroff)的动作

halt

关闭系统

[root@master shell_learning]# halt

halt -p

关闭系统并关闭电源

[root@master shell_learning]# halt -p

halt -d

关闭系统,但不留下纪录

[root@master shell_learning]# halt -d

id

id 会显示用户以及所属群组的实际与有效 ID。若两个 ID 相同,则仅显示实际 ID。若仅指定用户名称,则显示目前用户的 ID。

参数

  • -g或--group  显示用户所属群组的ID。
  • -G或--groups  显示用户所属附加群组的ID。
  • -n或--name  显示用户,所属群组或附加群组的名称。
  • -r或--real  显示实际ID。
  • -u或--user  显示用户ID。
  • -help  显示帮助。
  • -version  显示版本信息。

 id

显示当前用户信息。

[looking@master ~]$ id
uid=1000(looking) gid=1000(looking) groups=1000(looking) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

id looking 

显示指定用户信息。

[looking@master ~]$ id looking
uid=1000(looking) gid=1000(looking) groups=1000(looking)

id -g 

显示用户群组的 ID。

[looking@master ~]$ id -g
1000

id -un 

显示当前用户名称。

[looking@master ~]$ id -un
looking

kill

kill 命令用于删除执行中的程序或工作。kill 可将指定的信息送至程序。预设的信息为 SIGTERM(15),可将指定程序终止。若仍无法终止该程序,可使用 SIGKILL(9) 信息尝试强制删除程序。程序或工作的编号可利用 ps 指令或 jobs 指令查看。

参数

  • -l <信息编号>  若不加<信息编号>选项,则 -l 参数会列出全部的信息名称。
  • -s <信息名称或编号>  指定要送出的信息。
  • [程序]  [程序]可以是程序的PID或是PGID,也可以是工作编号。

使用 kill -l 命令列出所有可用信号。

最常用的信号是:

  • 1 (HUP):重新加载进程。
  • 9 (KILL):杀死一个进程。
  • 15 (TERM):正常停止一个进程。

kill -l

显示信号

[root@master shell_learning]# kill -l
 1) SIGHUP	 2) SIGINT	 3) SIGQUIT	 4) SIGILL	 5) SIGTRAP
 6) SIGABRT	 7) SIGBUS	 8) SIGFPE	 9) SIGKILL	10) SIGUSR1
11) SIGSEGV	12) SIGUSR2	13) SIGPIPE	14) SIGALRM	15) SIGTERM
16) SIGSTKFLT	17) SIGCHLD	18) SIGCONT	19) SIGSTOP	20) SIGTSTP
21) SIGTTIN	22) SIGTTOU	23) SIGURG	24) SIGXCPU	25) SIGXFSZ
26) SIGVTALRM	27) SIGPROF	28) SIGWINCH	29) SIGIO	30) SIGPWR
31) SIGSYS	34) SIGRTMIN	35) SIGRTMIN+1	36) SIGRTMIN+2	37) SIGRTMIN+3
38) SIGRTMIN+4	39) SIGRTMIN+5	40) SIGRTMIN+6	41) SIGRTMIN+7	42) SIGRTMIN+8
43) SIGRTMIN+9	44) SIGRTMIN+10	45) SIGRTMIN+11	46) SIGRTMIN+12	47) SIGRTMIN+13
48) SIGRTMIN+14	49) SIGRTMIN+15	50) SIGRTMAX-14	51) SIGRTMAX-13	52) SIGRTMAX-12
53) SIGRTMAX-11	54) SIGRTMAX-10	55) SIGRTMAX-9	56) SIGRTMAX-8	57) SIGRTMAX-7
58) SIGRTMAX-6	59) SIGRTMAX-5	60) SIGRTMAX-4	61) SIGRTMAX-3	62) SIGRTMAX-2
63) SIGRTMAX-1	64) SIGRTMAX	

kill 12345

杀死进程

[root@master shell_learning]# kill 12345

kill -9 12345

彻底杀死进程

[root@master shell_learning]# kill -9 12345

last

last 命令用于显示用户最近登录信息。

参数

  • -R 省略 hostname 的栏位
  • -num 展示前 num 个
  • username 展示 username 的登入讯息
  • tty 限制登入讯息包含终端机代号

last

[root@master shell_learning]# last
root     pts/1        192.168.128.1    Sun Oct 11 01:28   still logged in   
looking  pts/0        192.168.128.1    Sun Oct 11 01:28   still logged in   
reboot   system boot  3.10.0-957.el7.x Sun Oct 11 01:27 - 01:40  (00:13)    
root     pts/1        192.168.128.1    Sat Oct 10 17:00 - down   (00:25)    
root     pts/1        192.168.128.1    Sat Oct 10 22:31 - 17:00  (-5:-30)   
looking  pts/0        192.168.128.1    Sat Oct 10 22:18 - 17:26  (-4:-52)   
root     pts/1        192.168.128.1    Sat Oct 10 21:00 - 22:30  (01:29)    
looking  pts/0        192.168.128.1    Sat Oct 10 20:56 - 22:18  (01:21)    
root     pts/2        192.168.128.1    Sat Oct 10 20:26 - 20:57  (00:31)    
root     pts/1        192.168.128.1    Sat Oct 10 20:21 - 21:00  (00:38)    
root     pts/1        192.168.128.1    Sat Oct 10 20:04 - 20:21  (00:16)    
root     pts/0        192.168.128.1    Sat Oct 10 19:11 - 20:37  (01:25)    
reboot   system boot  3.10.0-957.el7.x Sat Oct 10 19:11 - 17:26  (-1:-45)   
root     pts/1        192.168.128.1    Fri Oct  9 22:48 - crash  (20:23)    
root     pts/0        192.168.128.1    Fri Oct  9 22:31 - 00:59  (02:27)    
root     pts/0        192.168.128.1    Fri Oct  9 22:30 - 22:31  (00:00)    
reboot   system boot  3.10.0-957.el7.x Fri Oct  9 22:30 - 17:26  (18:55)    
root     pts/0        192.168.128.1    Fri Oct  9 22:27 - crash  (00:02)    
reboot   system boot  3.10.0-957.el7.x Fri Oct  9 22:27 - 17:26  (18:58)    
root     pts/0        192.168.128.1    Fri Oct  9 22:20 - crash  (00:06)    
reboot   system boot  3.10.0-957.el7.x Fri Oct  9 22:20 - 17:26  (19:05)    
root     pts/0        192.168.128.1    Thu Oct  1 00:58 - crash (8+21:21)   
root     tty1                          Thu Oct  1 00:56 - crash (8+21:23)   
reboot   system boot  3.10.0-957.el7.x Thu Oct  1 00:56 - 17:26 (9+16:29)   
root     tty1                          Thu Oct  1 00:37 - crash  (00:19)    
reboot   system boot  3.10.0-957.el7.x Thu Oct  1 00:36 - 17:26 (9+16:49)   

wtmp begins Thu Oct  1 00:36:54 2020

last -R -2 

[root@master shell_learning]# last -R -5
root     pts/1        Sun Oct 11 01:28   still logged in   
looking  pts/0        Sun Oct 11 01:28   still logged in   
reboot   system boot  Sun Oct 11 01:27 - 01:48  (00:20)    
root     pts/1        Sat Oct 10 17:00 - down   (00:25)    
root     pts/1        Sat Oct 10 22:31 - 17:00  (-5:-30)   

wtmp begins Thu Oct  1 00:36:54 2020

last -5n -ai 

[root@master shell_learning]# last -5n -ai
root     pts/1        192.168.128.1    Sun Oct 11 01:28   still logged in   
looking  pts/0        192.168.128.1    Sun Oct 11 01:28   still logged in   
reboot   system boot  3.10.0-957.el7.x Sun Oct 11 01:27 - 01:47  (00:20)    
root     pts/1        192.168.128.1    Sat Oct 10 17:00 - down   (00:25)    
root     pts/1        192.168.128.1    Sat Oct 10 22:31 - 17:00  (-5:-30)   
looking  pts/0        192.168.128.1    Sat Oct 10 22:18 - 17:26  (-4:-52)   
root     pts/1        192.168.128.1    Sat Oct 10 21:00 - 22:30  (01:29)    
looking  pts/0        192.168.128.1    Sat Oct 10 20:56 - 22:18  (01:21)    
root     pts/2        192.168.128.1    Sat Oct 10 20:26 - 20:57  (00:31)    
root     pts/1        192.168.128.1    Sat Oct 10 20:21 - 21:00  (00:38)    
root     pts/1        192.168.128.1    Sat Oct 10 20:04 - 20:21  (00:16)    
root     pts/0        192.168.128.1    Sat Oct 10 19:11 - 20:37  (01:25)    
reboot   system boot  3.10.0-957.el7.x Sat Oct 10 19:11 - 17:26  (-1:-45)   
root     pts/1        192.168.128.1    Fri Oct  9 22:48 - crash  (20:23)    
root     pts/0        192.168.128.1    Fri Oct  9 22:31 - 00:59  (02:27)    
root     pts/0        192.168.128.1    Fri Oct  9 22:30 - 22:31  (00:00)    
reboot   system boot  3.10.0-957.el7.x Fri Oct  9 22:30 - 17:26  (18:55)    
root     pts/0        192.168.128.1    Fri Oct  9 22:27 - crash  (00:02)    
reboot   system boot  3.10.0-957.el7.x Fri Oct  9 22:27 - 17:26  (18:58)    
root     pts/0        192.168.128.1    Fri Oct  9 22:20 - crash  (00:06)    
reboot   system boot  3.10.0-957.el7.x Fri Oct  9 22:20 - 17:26  (19:05)    
root     pts/0        192.168.128.1    Thu Oct  1 00:58 - crash (8+21:21)   
root     tty1                          Thu Oct  1 00:56 - crash (8+21:23)   
reboot   system boot  3.10.0-957.el7.x Thu Oct  1 00:56 - 17:26 (9+16:29)   
root     tty1                          Thu Oct  1 00:37 - crash  (00:19)    
reboot   system boot  3.10.0-957.el7.x Thu Oct  1 00:36 - 17:26 (9+16:49)   

wtmp begins Thu Oct  1 00:36:54 2020

lastb

lastb 命令用于列出登入系统失败的用户相关信息。单独执行 lastb 指令,它会读取位于 /var/log 目录下,名称为 btmp 的文件,并把该文件内容记录的登入失败的用户名单,全部显示出来。

参数

  • -a  把从何处登入系统的主机名称或IP地址显示在最后一行。
  • -d  将IP地址转换成主机名称。
  • -f<记录文件>  指定记录文件。
  • -n<显示列数>或-<显示列数>  设置列出名单的显示列数。
  • -R  不显示登入系统的主机名称或IP地址。
  • -x  显示系统关机,重新开机,以及执行等级的改变等信息。

lastb

[root@master shell_learning]# lastb
(unknown tty1                          Mon Oct 12 18:11 - 18:11  (00:00)    
(unknown tty1                          Mon Oct 12 18:11 - 18:11  (00:00)    
looking  tty1                          Mon Oct 12 18:10 - 18:10  (00:00)    

btmp begins Mon Oct 12 18:10:55 2020

# 如果账号被尝试登录失败的话,正常登录的用户会看到有人尝试登陆失败的提示哟!
The remote SSH server rejected X11 forwarding request.
Last failed login: Mon Oct 12 18:10:55 CST 2020 on tty1
There was 1 failed login attempt since the last successful login.
Last login: Mon Oct 12 10:25:25 2020

login

login 命令用于登入系统。login 指令让用户登入系统,您亦可通过它的功能随时更换登入身份。在 Slackware 发行版中 ,您可在指令后面附加欲登入的用户名称,它会直接询问密码,等待用户输入。当 /etc 目录里含名称为 nologin 的文件时,系统只 root 账号登入系统,其他用户一律不准登入。

logname

logname 命令用于显示用户名称。执行 logname 指令,它会显示目前用户的名称。

参数

  • --help  在线帮助。
  • --vesion  显示版本信息。

logname

[root@master shell_learning]# logname
root

logout

logout 命令用于退出系统。logout 指令让用户退出系统,其功能和 login 指令相互对应。

newgrp

newgrp 命令用于登入另一个群组(切换有效群组)。newgrp 指令类似 login 指令,当它是以相同的帐号,另一个群组名称,再次登入系统。欲使用 newgrp 指令切换群组,您必须是该群组的用户,否则将无法登入指定的群组。单一用户要同时隶属多个群组,需利用交替用户的设置。若不指定群组名称,则 newgrp 指令会登入该用户名称的预设群组。

Linux 基础命令学习_第2张图片

poweroff

poweroff 命令命令用于关闭计算器并切断电源。

参数

  • -n : 在关机前不做将记忆体资料写回硬盘的动作
  • -w : 并不会真的关机,只是把记录写到 /var/log/wtmp 档案里
  • -d : 不把记录写到 /var/log/wtmp 文件里
  • -i : 在关机之前先把所有网络相关的装置先停止
  • -p : 关闭操作系统之前将系统中所有的硬件设置为备用模式。

ps

ps 命令用于显示当前进程的状态,类似于 windows 的任务管理器。

参数

  • -A 列出所有的行程
  • -w 显示加宽可以显示较多的资讯
  • -au 显示较详细的资讯
  • -aux 显示所有包含其他使用者的行程
  • au(x) 输出格式 :
  • USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
  • USER: 行程拥有者
  • PID: pid
  • %CPU: 占用的 CPU 使用率
  • %MEM: 占用的记忆体使用率
  • VSZ: 占用的虚拟记忆体大小
  • RSS: 占用的记忆体大小
  • TTY: 终端的次要装置号码 (minor device number of tty)
  • STAT: 该行程的状态:
  • D: 无法中断的休眠状态 (通常 IO 的进程)
  • R: 正在执行中
  • S: 静止状态
  • T: 暂停执行
  • Z: 不存在但暂时无法消除
  • W: 没有足够的记忆体分页可分配
  • <: 高优先序的行程
  • N: 低优先序的行程
  • L: 有记忆体分页分配并锁在记忆体内 (实时系统或捱A I/O)
  • START: 行程开始时间
  • TIME: 执行的时间
  • COMMAND:所执行的指令

ps

[root@master shell_learning]# ps
   PID TTY          TIME CMD
  8289 pts/1    00:00:00 bash
  8310 pts/1    00:00:00 ps

ps -aux | grep sbin (常用)

[root@master shell_learning]# ps -aux | grep sbin
root       3125  0.0  0.3 127348  6172 ?        Ss   09:52   0:00 /usr/sbin/lvmetad -f
root       5523  0.0  0.0  55520   900 ?        S

ps -ef | grep sbin

和 ps -aux | grep "sbin" (常用)功能类似,展示风格不太一样。

[root@master shell_learning]# ps -ef | grep sbin
root       3125      1  0 09:52 ?        00:00:00 /usr/sbin/lvmetad -f
root       5523      1  0 09:52 ?        00:00:00 /sbin/auditd
rpc        6043      1  0 09:52 ?        00:00:00 /sbin/rpcbind -w
root       6058      1  0 09:52 ?        00:00:00 /usr/sbin/abrtd -d -s
root       6344      1  0 09:52 ?        00:00:00 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid
root       6351      1  0 09:52 ?        00:00:00 /usr/sbin/crond -n
root       6611      1  0 09:52 ?        00:00:00 /usr/sbin/NetworkManager --no-daemon
root       7535      1  0 09:52 ?        00:00:00 /usr/sbin/sshd -D
root       7536      1  0 09:52 ?        00:00:00 /usr/bin/python2 -Es /usr/sbin/tuned -l -P
root       7538      1  0 09:52 ?        00:00:00 /usr/sbin/rsyslogd -n
root       8080      1  0 10:00 ?        00:00:00 /usr/sbin/anacron -s
root       8342   8289  0 10:49 pts/1    00:00:00 grep --color=auto sbin

pstree

pstree 命令将所有行程以树状图显示,树状图将会以 pid (如果有指定) 或是以 init 这个基本行程为根 (root),如果有指定使用者 id,则树状图会只显示该使用者所拥有的行程。

语法

pstree [-a] [-c] [-h|-Hpid] [-l] [-n] [-p] [-u] [-G|-U] [pid|user]

参数

  • -a 显示该行程的完整指令及参数, 如果是被记忆体置换出去的行程则会加上括号
  • -c 如果有重覆的行程名, 则分开列出(预设值是会在前面加上 *)

pstree

[looking@master ~]$ pstree
systemd─┬─NetworkManager───2*[{NetworkManager}]
        ├─VGAuthService
        ├─auditd───{auditd}
        ├─chronyd
        ├─crond
        ├─dbus-daemon───{dbus-daemon}
        ├─irqbalance
        ├─java───53*[{java}]
        ├─login───bash
        ├─lvmetad
        ├─master─┬─pickup
        │        └─qmgr
        ├─mysqld───29*[{mysqld}]
        ├─polkitd───6*[{polkitd}]
        ├─rsyslogd───2*[{rsyslogd}]
        ├─sshd─┬─sshd───bash─┬─pry
        │      │             ├─4*[python3]
        │      │             └─2*[python3.6]
        │      ├─sshd───sshd───bash─┬─python
        │      │                    └─python3
        │      └─sshd───sshd───bash───pstree
        ├─systemd-journal
        ├─systemd-logind
        ├─systemd-udevd
        ├─tuned───4*[{tuned}]
        └─vmtoolsd───{vmtoolsd}

reboot

reboot 命令用于用来重新启动计算机。若系统 runlevel 为 0 或 6 则重新开机,否则以 shutdown 指令(加上 -r 参数)来取代。

参数

  • -n : 在重开机前不做将记忆体资料写回硬盘的动作
  • -w : 并不会真的重开机,只是把记录写到 /var/log/wtmp 档案里
  • -d : 不把记录写到 /var/log/wtmp 档案里(-n 这个参数包含了 -d)
  • -f : 强迫重开机,不呼叫 shutdown 这个指令
  • -i : 在重开机之前先把所有网络相关的装置先停止

reboot

普通用户使用需要 root 操作授权哟。

[looking@master ~]$ reboot
User root is logged in on sshd.
Please retry operation after closing inhibitors and logging out other users.
Alternatively, ignore inhibitors and users with 'systemctl reboot -i'.

[looking@master ~]$ reboot
==== AUTHENTICATING FOR org.freedesktop.login1.reboot ===
Authentication is required for rebooting the system.
Authenticating as: looking,anywhere,9999999,8888888 (root)
Password: 

shutdown

shutdown 命令可以用来进行关机程序,并且在关机以前传送讯息给所有使用者正在执行的程序,shutdown 也可以用来重开机。

参数

  • -t seconds : 设定在几秒钟之后进行关机程序。
  • -k : 并不会真的关机,只是将警告讯息传送给所有使用者。
  • -r : 关机后重新开机。
  • -h : 关机后停机。
  • -n : 不采用正常程序来关机,用强迫的方式杀掉所有执行中的程序后自行关机。
  • -c : 取消目前已经进行中的关机动作。
  • -f : 关机时,不做 fcsk 动作(检查 Linux 档系统)。
  • -F : 关机时,强迫进行 fsck 动作。
  • time : 设定关机的时间。
  • message : 传送给所有使用者的警告讯息。

shutdown -h now

立即关机

[root@master shell_learning]# shutdown -h now

shutdown -h 10 

指定 10 分钟后关机 (后面直接跟数字的话默认是以分钟为单位)。

[root@master shell_learning]# shutdown -h 10
Broadcast message from root@master (Mon 2020-10-12 11:47:35 CST):

The system is going down for power-off at Mon 2020-10-12 11:57:35 CST!

shutdown -k 10 (用来吓人的)

只是将警告讯息传送给所有使用者,并不会真的关机。

[root@master shell_learning]# shutdown -k 10
Shutdown scheduled for Mon 2020-10-12 11:58:33 CST, use 'shutdown -c' to cancel.

Broadcast message from root@master (Mon 2020-10-12 11:48:33 CST):

The system is going down for power-off at Mon 2020-10-12 11:58:33 CST!

shutdown -r now

重新启动计算机 

[root@master shell_learning]# shutdown -r now

shutdown -c

取消目前已经进行中的关机动作(这个是给你的后悔药,万一你又不想关了呢)。

[root@master shell_learning]# shutdown -c

Broadcast message from root@master (Mon 2020-10-12 11:54:52 CST):

The system shutdown has been cancelled at Mon 2020-10-12 11:55:52 CST!

sleep

sleep 命令可以用来将目前动作延迟一段时间(默认计时单位为秒)。

参数

  • --help : 显示辅助讯息
  • --version : 显示版本编号
  • number : 时间长度,后面可接 s、m、h 或 d
  • 其中 s 为秒,m 为 分钟,h 为小时,d 为日数

sleep 5s

[root@master shell_learning]# sleep 5s

date;sleep 10s;date 

[root@master shell_learning]# date;sleep 10s;date
Sat Oct 10 16:56:56 CST 2020
Sat Oct 10 16:57:06 CST 2020

su

su(swith user)命令用于变更为其他使用者的身份,除 root 外,需要键入该使用者的密码。

参数

  • -f 或 --fast 不必读启动档(如 csh.cshrc 等),仅用于 csh 或 tcsh
  • -m -p 或 --preserve-environment 执行 su 时不改变环境变数
  • -c command 或 --command=command 变更为帐号为 USER 的使用者并执行指令(command)后再变回原来使用者
  • -s shell 或 --shell=shell 指定要执行的 shell (bash csh tcsh 等),预设值为 /etc/passwd 内的该使用者(USER) shell
  • --help 显示说明文件
  • --version 显示版本资讯
  • - -l 或 --login 这个参数加了之后,就好像是重新 login 为该使用者一样,大部份环境变数(HOME,SHELL,USER等等)都是以该使用者(USER)为主,并且工作目录也会改变,如果没有指定 USER ,内定是 root。
  • USER 欲变更的使用者帐号
  • ARG 传入新的 shell 参数

su (默认变更到 root)

[looking@master ~]$ su 
Password: 
[root@master looking]# 

su test 

变更为指定身份。

[looking@master ~]$ su test
Password: 
[test@master looking]$ 

su root -c ls

变更帐号为 root(环境没变,导致 ls 仍然显示的当前目录的内容)并在执行 ls 指令后退出变回原使用者。

[looking@master ~]$ su root -c ls
Password: 
accounts.json  GitTest	load_test_data.sh  packages  ruby_learning  test.json  test.txt  workspace

su - root -c ls 

变更帐号为 root(环境也变了,导致 ls 仍然显示的为 root 目录下的内容)并在执行 ls 指令后退出变回原使用者。

[looking@master ~]$ su - root -c ls
Password: 
bisectercise  deep_learning   docker	git	 id_rsa.pub  packages	  recyclebin   test.sh
date.sh       django_project  first-pr	GitTest  looking     pycorrector  render.html  workspace

sudo

sudo 命令以系统管理者的身份执行指令,也就是说,经由 sudo 所执行的指令就好像是 root 亲自执行。

使用权限:在 /etc/sudoers 中有出现的使用者。

Linux 基础命令学习_第3张图片

Linux 基础命令学习_第4张图片

sudo yum install gcc

[looking@master ~]$ yum install gcc
Loaded plugins: fastestmirror
You need to be root to perform this command.
[looking@master ~]$ sudo yum install gcc
[sudo] password for looking: 
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.tuna.tsinghua.edu.cn
 * updates: mirrors.aliyun.com
base 
...

sudo -V 

列出 sudo 的版本信息。

[looking@master ~]$ sudo -V
Sudo version 1.8.23
Sudoers policy plugin version 1.8.23
Sudoers file grammar version 46
Sudoers I/O plugin version 1.8.23

sudo -h

指令的使用方式说明。

[looking@master ~]$ sudo -h
sudo - execute a command as another user

usage: sudo -h | -K | -k | -V
usage: sudo -v [-AknS] [-g group] [-h host] [-p prompt] [-u user]
usage: sudo -l [-AknS] [-g group] [-h host] [-p prompt] [-U user] [-u user] [command]
usage: sudo [-AbEHknPS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p prompt] [-T timeout] [-u user]
            [VAR=value] [-i|-s] []
usage: sudo -e [-AknS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p prompt] [-T timeout] [-u user] file ...

Options:
  -A, --askpass                 use a helper program for password prompting
  -b, --background              run command in the background
  -C, --close-from=num          close all file descriptors >= num
  -E, --preserve-env            preserve user environment when running command
      --preserve-env=list       preserve specific environment variables
  -e, --edit                    edit files instead of running a command
  -g, --group=group             run command as the specified group name or ID
  -H, --set-home                set HOME variable to target user's home dir
  -h, --help                    display help message and exit
  -h, --host=host               run command on host (if supported by plugin)
  -i, --login                   run login shell as the target user; a command may also be specified
  -K, --remove-timestamp        remove timestamp file completely
  -k, --reset-timestamp         invalidate timestamp file
  -l, --list                    list user's privileges or check a specific command; use twice for longer format
  -n, --non-interactive         non-interactive mode, no prompts are used
  -P, --preserve-groups         preserve group vector instead of setting to target's
  -p, --prompt=prompt           use the specified password prompt
  -r, --role=role               create SELinux security context with specified role
  -S, --stdin                   read password from standard input
  -s, --shell                   run shell as the target user; a command may also be specified
  -t, --type=type               create SELinux security context with specified type
  -T, --command-timeout=timeout terminate command after the specified time limit
  -U, --other-user=user         in list mode, display privileges for user
  -u, --user=user               run command (or edit file) as specified user name or ID
  -V, --version                 display version information and exit
  -v, --validate                update user's timestamp without running a command
  --                            stop processing command line arguments
[looking@master ~]$ sudo
usage: sudo -h | -K | -k | -V
usage: sudo -v [-AknS] [-g group] [-h host] [-p prompt] [-u user]
usage: sudo -l [-AknS] [-g group] [-h host] [-p prompt] [-U user] [-u user] [command]
usage: sudo [-AbEHknPS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p prompt] [-T timeout] [-u user]
            [VAR=value] [-i|-s] []
usage: sudo -e [-AknS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p prompt] [-T timeout] [-u user] file ...

sudo -l 

显示自己(执行 sudo 的使用者)的权限。

[looking@master ~]$ sudo -l
[sudo] password for looking: 
Matching Defaults entries for looking on master:
    !visiblepw, always_set_home, match_group_by_gid, always_query_group_plugin, env_reset, env_keep="COLORS DISPLAY
    HOSTNAME HISTSIZE KDEDIR LS_COLORS", env_keep+="MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE",
    env_keep+="LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES", env_keep+="LC_MONETARY LC_NAME LC_NUMERIC
    LC_PAPER LC_TELEPHONE", env_keep+="LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY",
    secure_path=/sbin\:/bin\:/usr/sbin\:/usr/bin

User looking may run the following commands on master:
    (ALL) ALL

sudo -k

将会强迫使用者在下一次执行 sudo 时问密码(不论有没有超过 N 分钟)。 

[looking@master ~]$ sudo -k

sudo -s

执行环境变数中的 SHELL 所指定的 shell ,或是 /etc/passwd 里所指定的 shell。 

[looking@master ~]$ sudo -s
[root@master looking]#

suspend

suspend 命令用于暂停执行 shell。suspend 为 shell 内建指令,可暂停目前正在执行的 shell。若要恢复,则必须使用 SIGCONT信息。

参数

  • -f  若目前执行的 shell 为登入的 shell,则 suspend 预设无法暂停此 shell。若要强迫暂停登入的 shell,则必须使用-f参数

suspend

[root@master shell_learning]# suspend
-bash: suspend: cannot suspend a login shell
[root@master shell_learning]# suspend -f

tload

tload 命令用于显示系统负载状况。tload 指令使用 ASCII 字符简单地以文字模式显示系统负载状态。假设不给予终端机编号,则会在执行 tload 指令的终端机显示负载情形。

参数

  • -d<间隔秒数>  设置tload检测系统负载的间隔时间,单位以秒计算。
  • -s<刻度大小>  设置图表的垂直刻度大小,单位以列计算。
  • -V  显示版本信息。

 tload

[root@master shell_learning]# tload
 0.00, 0.01, 0.05 

top

top 命令用于实时显示 process 的动态。

参数

  • d : 改变显示的更新速度,或是在交谈式指令列( interactive command)按 s
  • q : 没有任何延迟的显示速度,如果使用者是有 superuser 的权限,则 top 将会以最高的优先序执行
  • c : 切换显示模式,共有两种模式,一是只显示执行档的名称,另一种是显示完整的路径与名称S : 累积模式,会将己完成或消失的子行程 ( dead child process ) 的 CPU time 累积起来
  • s : 安全模式,将交谈式指令取消, 避免潜在的危机
  • i : 不显示任何闲置 (idle) 或无用 (zombie) 的行程
  • n : 更新的次数,完成后将会退出 top
  • b : 批次档模式,搭配 "n" 参数一起使用,可以用来将 top 的结果输出到档案内

top

[root@master shell_learning]# top
top - 11:02:02 up  1:09,  3 users,  load average: 0.00, 0.01, 0.05
Tasks: 105 total,   1 running, 104 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.3 sy,  0.0 ni, 99.3 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  1863224 total,  1400168 free,   149656 used,   313400 buff/cache
KiB Swap:  2097148 total,  2097148 free,        0 used.  1519168 avail Mem 

   PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND                                           
 11573 root      20   0       0      0      0 S  0.3  0.0   0:00.08 kworker/0:0                                       
     1 root      20   0  128488   7028   4140 S  0.0  0.4   0:01.82 systemd                                           
     2 root      20   0       0      0      0 S  0.0  0.0   0:00.00 kthreadd                                          
     3 root      20   0       0      0      0 S  0.0  0.0   0:00.15 ksoftirqd/0                                       
     5 root       0 -20       0      0      0 S  0.0  0.0   0:00.00 kworker/0:0H                                      
     6 root      20   0       0      0      0 S  0.0  0.0   0:00.00 kworker/u256

top -p 10 

[root@master shell_learning]# top -p 10
top - 11:04:15 up  1:12,  3 users,  load average: 0.00, 0.01, 0.05
Tasks:   1 total,   0 running,   1 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.3 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  1863224 total,  1400292 free,   149544 used,   313388 buff/cache
KiB Swap:  2097148 total,  2097148 free,        0 used.  1519296 avail Mem 

   PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND                                           
    10 root       0 -20       0      0      0 S  0.0  0.0   0:00.00 lru-add-drain 

top -p 139

显示进程号为 139 的进程信息,CPU、内存占用率等。

[root@master shell_learning]# top -p 139

top -d 3

设置信息更新时间为 3 秒。

[root@master shell_learning]# top -d 3

uname

uname 命令用于显示系统信息。uname 可显示电脑以及操作系统的相关信息。

参数

  • -a或--all  显示全部的信息。
  • -m或--machine  显示电脑类型。
  • -n或-nodename  显示在网络上的主机名称。
  • -r或--release  显示操作系统的发行编号。
  • -s或--sysname  显示操作系统名称。
  • -v  显示操作系统的版本。
  • --help  显示帮助。
  • --version  显示版本信息。

uname

同 uname -s,显示操作系统名称。

[root@master shell_learning]# uname
Linux

uname -a 

显示系统详细信息。

[root@master shell_learning]# uname -a
Linux master 3.10.0-957.el7.x86_64 #1 SMP Thu Nov 8 23:39:32 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

uname -m 

显示主机类型。

[root@master shell_learning]# uname -m
x86_64

uname -n

显示主机名称。

[root@master shell_learning]# uname -n
master

uname -r

显示操作系统发行编号。

[root@master shell_learning]# uname -r
3.10.0-957.el7.x86_64

uname -s 

显示操作系统名称。

[root@master shell_learning]# uname -s
Linux

uname -v

显示系统版本与时间。

[root@master shell_learning]# uname  -v
#1 SMP Thu Nov 8 23:39:32 UTC 2018

useradd

useradd 命令用于建立用户帐号。useradd 可用来建立用户帐号。帐号建好之后,再用 passwd 设定帐号的密码。而可用 userdel 删除帐号。使用 useradd 指令所建立的帐号,实际上是保存在 /etc/passwd 文本文件中。

参数

  • -c<备注>  加上备注文字。备注文字会保存在passwd的备注栏位中。
  • -d<登入目录>  指定用户登入时的起始目录。
  • -D  变更预设值.
  • -e<有效期限>  指定帐号的有效期限。
  • -f<缓冲天数>  指定在密码过期后多少天即关闭该帐号。
  • -g<群组>  指定用户所属的群组。
  • -G<群组>  指定用户所属的附加群组。
  • -m  自动建立用户的登入目录。
  • -M  不要自动建立用户的登入目录。
  • -n  取消建立以用户名称为名的群组.
  • -r  建立系统帐号。
  • -s   指定用户登入后所使用的shell。
  • -u  指定用户ID。

useradd tt

添加一般用户

[root@master shell_learning]# useradd tt

useradd -g root tt 

为添加的用户指定相应的用户组

[root@master shell_learning]# useradd -g root tt

 useradd -d /home/tst test

为新添加的用户指定home目录

[root@master shell_learning]# useradd -d /home/tst test
[root@master shell_learning]# cd /home/tst/

userdel

userdel 命令用于删除用户帐号。userdel 可删除用户帐号与相关的文件。若不加参数,则仅删除用户帐号,而不删除相关文件。

参数说明

  • -r  删除用户登入目录以及目录中所有文件。

userdel tt

[root@master shell_learning]# userdel tt

userdel -r test

[root@master shell_learning]# userdel -r test

usermod

usermod 命令用于修改用户帐号。usermod 可用来修改用户帐号的各项设定。

参数

  • -c<备注>  修改用户帐号的备注文字。
  • -d<登入目录>  修改用户登入时的目录。
  • -e<有效期限>  修改帐号的有效期限。
  • -f<缓冲天数>  修改在密码过期后多少天即关闭该帐号。
  • -g<群组>  修改用户所属的群组。
  • -G<群组>  修改用户所属的附加群组。
  • -l<帐号名称>  修改用户帐号名称。
  • -L  锁定用户密码,使密码无效。
  • -s  修改用户登入后所使用的shell。
  • -u  修改用户ID。
  • -U  解除密码锁定。

usermod -d /home/hnlinux root

[root@master shell_learning]# usermod -d /home/hnlinux root

uuidgen

UUID码全称是通用唯一识别码 (Universally Unique Identifier, UUID) ,Unix/Linux 环境中大都有一个名为 uuidgen 的小工具,运行即可生成一个 UUID 到标准输出。

[root@master ~]# uuidgen
014b3e70-e4a2-42d5-bb5e-1f8b06107c24

vlock

vlock 命令用于锁住虚拟终端。执行 vlock(virtual console lock) 指令可锁住虚拟终端,避免他人使用。

参数

  • -a或--all  锁住所有的终端阶段作业,如果您在全屏幕的终端中使用本参数,则会将用键盘
  • 切换终端机的功能一并关闭。
  • -c或--current  锁住目前的终端阶段作业,此为预设值。
  • -h或--help  在线帮助。
  • -v或--version  显示版本信息。

vlock

[looking@master shell_learning]# vlock
This tty (pts/3) is not a virtual console.


The pts/3 is now locked by looking.
Password: 

w

w 命令用于显示目前登入系统的用户信息。执行这项指令可得知目前登入系统的用户有哪些人,以及他们正在执行的程序。

单独执行 w 指令会显示所有的用户,您也可指定用户名称,仅显示某位用户的相关信息。

参数

  • -f  开启或关闭显示用户从何处登入系统。
  • -h  不显示各栏位的标题信息列。
  • -l  使用详细格式列表,此为预设值。
  • -s  使用简洁格式列表,不显示用户登入时间,终端机阶段作业和程序所耗费的CPU时间。
  • -u  忽略执行程序的名称,以及该程序耗费CPU时间的信息。
  • -V  显示版本信息。

 w

显示当前用户

[looking@master ~]$ w
 15:30:59 up  1:59,  4 users,  load average: 0.00, 0.01, 0.05
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
looking  pts/0    192.168.128.1    11:41    3:49m  0.00s  0.00s -bash
root     pts/1    192.168.128.1    11:41    3:36m  0.03s  0.03s -bash
looking  pts/3    192.168.128.1    14:07    3.00s  0.04s  0.00s w
root     pts/2    192.168.128.1    14:07    5:39   0.08s  0.01s bash

w -f 

不显示登录位置。

[looking@master ~]$ w -f
 15:31:01 up  1:59,  4 users,  load average: 0.00, 0.01, 0.05
USER     TTY        LOGIN@   IDLE   JCPU   PCPU WHAT
looking  pts/0     11:41    3:49m  0.00s  0.00s -bash
root     pts/1     11:41    3:36m  0.03s  0.03s -bash
looking  pts/3     14:07    5.00s  0.04s  0.00s w -f
root     pts/2     14:07    5:41   0.08s  0.01s bash

w -s

精简模式显示。

[looking@master ~]$ w -s
 15:31:08 up  1:59,  4 users,  load average: 0.00, 0.01, 0.05
USER     TTY      FROM              IDLE WHAT
looking  pts/0    192.168.128.1     3:50m -bash
root     pts/1    192.168.128.1     3:36m -bash
looking  pts/3    192.168.128.1     4.00s w -s
root     pts/2    192.168.128.1     5:48  bash

who

who 命令用于显示系统中有哪些使用者正在上面,显示的资料包含了使用者 ID、使用的终端机、从哪边连上来的、上线时间、呆滞时间、CPU 使用量、动作等等。

参数

  • -H 或 --heading:显示各栏位的标题信息列;
  • -i 或 -u 或 --idle:显示闲置时间,若该用户在前一分钟之内有进行任何动作,将标示成"."号,如果该用户已超过24小时没有任何动作,则标示出"old"字符串;
  • -m:此参数的效果和指定"am i"字符串相同;
  • -q 或--count:只显示登入系统的帐号名称和总人数;
  • -s:此参数将忽略不予处理,仅负责解决who指令其他版本的兼容性问题;
  • -w 或-T或--mesg或--message或--writable:显示用户的信息状态栏;
  • --help:在线帮助;
  • --version:显示版本信息。

who

显示当前登录系统的用户。

[root@master shell_learning]# who
looking  pts/0        2020-10-12 11:41 (192.168.128.1)
root     pts/1        2020-10-12 11:41 (192.168.128.1)
looking  pts/3        2020-10-12 14:07 (192.168.128.1)
root     pts/2        2020-10-12 14:07 (192.168.128.1)

who -H 

显示标题栏。

[root@master shell_learning]# who -H
NAME     LINE         TIME             COMMENT
looking  pts/0        2020-10-12 11:41 (192.168.128.1)
root     pts/1        2020-10-12 11:41 (192.168.128.1)
looking  pts/3        2020-10-12 14:07 (192.168.128.1)
root     pts/2        2020-10-12 14:07 (192.168.128.1)

who -TH 

显示终端属性。

[root@master shell_learning]# who -TH
NAME       LINE         TIME             COMMENT
looking  + pts/0        2020-10-12 11:41 (192.168.128.1)
root     + pts/1        2020-10-12 11:41 (192.168.128.1)
looking  + pts/3        2020-10-12 14:07 (192.168.128.1)
root     + pts/2        2020-10-12 14:07 (192.168.128.1)

who -mH 

只显示当前用户。

[root@master shell_learning]# who -mH
NAME     LINE         TIME             COMMENT
root     pts/2        2020-10-12 14:07 (192.168.128.1)

whoami

显示自身用户名称。 

[root@master shell_learning]# whoami
root

who am i 

显示用户详情。

[root@master shell_learning]# who am i
root     pts/2        2020-10-12 14:07 (192.168.128.1)

系统设置

alias/unalias

alias命令用于设置指令的别名。用户可利用 alias,自定指令的别名。若仅输入alias,则可列出目前所有的别名设置。alias的效力仅及于该次登入的操作。若要每次登入是即自动设好别名,可在 .profile 或 .cshrc 中设定指令的别名。

alias 

列出目前所有的别名设置。

[root@master shell_learning]# alias
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 lx='ls'
alias mv='mv -i'
alias rm='rm -i'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'

看到上面的 alias cp='cp -i' 了么?这就是为什么我们使用 cp -rf 了却还需要一个个去确认的原因(各发行版默认都会加上这个,可能是处于保护性的原因,怕用户误操作造成破坏):

[root@master insight-tools-env]# cp -rf config/conf-info/centos7.6/x86_64/ test
cp: overwrite ‘test/x86_64/device_interface.json’? y
cp: overwrite ‘test/x86_64/file_config_interface.json’? y
cp: overwrite ‘test/x86_64/hardware_configure.json’? y
cp: overwrite ‘test/x86_64/kernel_configure.json’? y
cp: overwrite ‘test/x86_64/kernel_startup_param.json’? y
cp: overwrite ‘test/x86_64/linux_command.json’? y
cp: overwrite ‘test/x86_64/path.json’? y
cp: overwrite ‘test/x86_64/port.json’? y
cp: overwrite ‘test/x86_64/proc.json’? y
cp: overwrite ‘test/x86_64/syscall_interface.json’? y
cp: overwrite ‘test/x86_64/system_configure.json’? y
cp: overwrite ‘test/x86_64/system_service.json’? y

 如果取消别名的话,cp -rf 是不再需要一个个去确认的:

[root@master insight-tools-env]# unalias cp
[root@master insight-tools-env]# cp -rf config/conf-info/centos7.6/x86_64/ test

当然,测试完以后,最好还是修改回去:

[root@master insight-tools-env]# alias cp='cp -i'

alias lx=ls 

添加别名。

[root@master shell_learning]# ls
test_dir  test.sh  test.txt
[root@master shell_learning]# lx
bash: lx: command not found
[root@master shell_learning]# alias lx=ls
[root@master shell_learning]# lx
test_dir  test.sh  test.txt

unalias lx 

删除别名。

[root@master shell_learning]# unalias lx

[root@master shell_learning]# alias
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'

bind

bind 命令用于显示或设置键盘按键与其相关的功能。

参数

  • -d  显示按键配置的内容。
  • -f<按键配置文件>  载入指定的按键配置文件。
  • -l  列出所有的功能。
  • -m<按键配置>  指定按键配置。
  • -q<功能>  显示指定功能的按键。
  • -v  列出目前的按键配置与其功能。

 bind -l

[root@master shell_learning]# bind -l
abort
accept-line
alias-expand-line
arrow-key-prefix
backward-byte
backward-char
...

chroot

chroot 命令用于改变根目录。chroot(change root)命令把根目录换成指定的目的目录。

clear

clear 命令用于清除屏幕,效果同 Ctrl + l 。

crontab

crontab 是用来定期执行程序的命令。当安装完成操作系统之后,默认便会启动此任务调度命令。

crond 命令每分锺会定期检查是否有要执行的工作,如果有要执行的工作便会自动执行该工作。

注意:新创建的 cron 任务,不会马上执行,至少要过 2 分钟后才可以,当然你可以重启 cron 来马上执行。

crontab 是用来让使用者在固定时间或固定间隔执行程序之用,换句话说,也就是类似使用者的时程表。

-u user 是指设定指定 user 的时程表,这个前提是你必须要有其权限(比如说是 root)才能够指定他人的时程表。如果不使用 -u user 的话,就是表示设定自己的时程表。

参数

  • -e : 执行文字编辑器来设定时程表,内定的文字编辑器是 VI,如果你想用别的文字编辑器,则请先设定 VISUAL 环境变数来指定使用那个文字编辑器(比如说 setenv VISUAL joe)
  • -r : 删除目前的时程表
  • -l : 列出目前的时程表

时间格式如下:

f1 f2 f3 f4 f5 program
  • 其中 f1 是表示分钟,f2 表示小时,f3 表示一个月份中的第几日,f4 表示月份,f5 表示一个星期中的第几天。program 表示要执行的程序。
  • 当 f1 为 * 时表示每分钟都要执行 program,f2 为 * 时表示每小时都要执行程序,其馀类推
  • 当 f1 为 a-b 时表示从第 a 分钟到第 b 分钟这段时间内要执行,f2 为 a-b 时表示从第 a 到第 b 小时都要执行,其馀类推
  • 当 f1 为 */n 时表示每 n 分钟个时间间隔执行一次,f2 为 */n 表示每 n 小时个时间间隔执行一次,其馀类推
  • 当 f1 为 a, b, c,... 时表示第 a, b, c,... 分钟要执行,f2 为 a, b, c,... 时表示第 a, b, c...个小时要执行,其馀类推
*    *    *    *    *
-    -    -    -    -
|    |    |    |    |
|    |    |    |    +----- 星期中星期几 (0 - 7) (星期天 为0)
|    |    |    +---------- 月份 (1 - 12) 
|    |    +--------------- 一个月中的第几天 (1 - 31)
|    +-------------------- 小时 (0 - 23)
+------------------------- 分钟 (0 - 59)

使用者也可以将所有的设定先存放在文件中,用 crontab file 的方式来设定执行时间。

实例

每一分钟执行一次 /bin/ls:

* * * * * /bin/ls

在 12 月内, 每天的早上 6 点到 12 点,每隔 3 个小时 0 分钟执行一次 /usr/bin/backup:

0 6-12/3 * 12 * /usr/bin/backup

周一到周五每天下午 5:00 寄一封信给 [email protected]

0 17 * * 1-5 mail -s "hi" [email protected] < /tmp/maildata

每月每天的午夜 0 点 20 分, 2 点 20 分, 4 点 20 分....执行 echo "haha":

20 0-23/2 * * * echo "haha"

下面再看看几个具体的例子:

0 */2 * * * /sbin/service httpd restart  意思是每两个小时重启一次apache 

50 7 * * * /sbin/service sshd start  意思是每天7:50开启ssh服务 

50 22 * * * /sbin/service sshd stop  意思是每天22:50关闭ssh服务 

0 0 1,15 * * fsck /home  每月1号和15号检查/home 磁盘 

1 * * * * /home/bruce/backup  每小时的第一分执行 /home/bruce/backup这个文件 

00 03 * * 1-5 find /home "*.xxx" -mtime +4 -exec rm {} \;  每周一至周五3点钟,在目录/home中,查找文件名为*.xxx的文件,并删除4天前的文件。

30 6 */10 * * ls  意思是每月的1、11、21、31日是的6:30执行一次ls命令

注意:当程序在你所指定的时间执行后,系统会发一封邮件给当前的用户,显示该程序执行的内容,若是你不希望收到这样的邮件,请在每一行空一格之后加上 > /dev/null 2>&1 即可,如:

20 03 * * * . /etc/profile;/bin/sh /var/www/runoob/test.sh > /dev/null 2>&1 

脚本无法执行问题:

如果我们使用 crontab 来定时执行脚本,无法执行,但是如果直接通过命令(如:./test.sh)又可以正常执行,这主要是因为无法读取环境变量的原因。

解决方法:

  • 1、所有命令需要写成绝对路径形式,如: /usr/local/bin/docker。

  • 2、在 shell 脚本开头使用以下代码:

    #!/bin/sh
    
    . /etc/profile
    . ~/.bash_profile

    3、在 /etc/crontab 中添加环境变量,在可执行命令之前添加命令 . /etc/profile;/bin/sh,使得好几遍了生效,例如:

    20 03 * * * . /etc/profile;/bin/sh /var/www/runoob/test.sh

declare

declare命令用于声明 shell 变量。declare 为 shell 指令,在第一种语法中可用来声明变量并设置变量的属性即为变量的属性),在第二种语法中可用来显示 shell 函数。若不加上任何参数,则会显示全部的 shell 变量与函数(与执行 set 指令的效果相同)。

参数

  • +/-  "-"可用来指定变量的属性,"+"则是取消变量所设的属性。
  • -f  仅显示函数。
  • r  将变量设置为只读。
  • x  指定的变量会成为环境变量,可供shell以外的程序来使用。
  • i  [设置值]可以是数值,字符串或运算式。

declare

显示全部的 shell 变量与函数。

[root@master shell_learning]# declare
BASH=/usr/bin/bash
BASHOPTS=checkwinsize:cmdhist:expand_aliases:extquote:force_fignore:histappend:hostcomplete:interactive_comments:progcomp:promptvars:sourcepath
BASH_ALIASES=()
BASH_ARGC=()
BASH_ARGV=()
BASH_CMDS=()
...

declare -i ab 

声明整数型变量。

[root@master shell_learning]# declare -i ab
[root@master shell_learning]# ab=56
[root@master shell_learning]# echo $ab
56

declare -r ab 

声明只读变量。

[root@master shell_learning]# declare -r ab
[root@master shell_learning]# ab=98
bash: ab: readonly variable
[root@master shell_learning]# echo $ab
56

declare -i ef

改变变量属性。

[root@master shell_learning]# declare -i ef
[root@master shell_learning]# ef=1
[root@master shell_learning]# echo $ef
1
[root@master shell_learning]# ef="Looking"
[root@master shell_learning]# echo $ef
0
[root@master shell_learning]# declare +i ef
[root@master shell_learning]# ef="Looking"
[root@master shell_learning]# echo $ef
Looking

dmesg

dmesg 命令用于显示开机信息。kernel 会将开机信息存储在 ring buffer 中。您若是开机时来不及查看信息,可利用 dmesg 来查看。开机信息亦保存在 /var/log 目录中,名称为 dmesg 的文件里。

参数

  • -c  显示信息后,清除ring buffer中的内容。
  • -s<缓冲区大小>  预设置为8196,刚好等于ring buffer的大小。
  • -n  设置记录信息的层级。

dmesg

[root@master shell_learning]# dmesg | less


[    0.000000] Initializing cgroup subsys cpuset
[    0.000000] Initializing cgroup subsys cpu
[    0.000000] Initializing cgroup subsys cpuacct
[    0.000000] Linux version 3.10.0-957.el7.x86_64 ([email protected]) (gcc version 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) ) #1 SMP Thu Nov 8 23:39:32 UTC 2018
[    0.000000] Command line: BOOT_IMAGE=/vmlinuz-3.10.0-957.el7.x86_64 root=/dev/mapper/centos-root ro crashkernel=auto rd.lvm.lv=centos/root rd.lvm.lv=centos/swap rhgb quiet LANG=en_US.UTF-8
[    0.000000] Disabled fast string operations
[    0.000000] e820: BIOS-provided physical RAM map:
[    0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000009ebff] usable
[    0.000000] BIOS-e820: [mem 0x000000000009ec00-0x000000000009ffff] reserved
[    0.000000] BIOS-e820: [mem 0x00000000000dc000-0x00000000000fffff] reserved
[    0.000000] BIOS-e820: [mem 0x0000000000100000-0x000000007fedffff] usable
[    0.000000] BIOS-e820: [mem 0x000000007fee0000-0x000000007fefefff] ACPI data
[    0.000000] BIOS-e820: [mem 0x000000007feff000-0x000000007fefffff] ACPI NVS
[    0.000000] BIOS-e820: [mem 0x000000007ff00000-0x000000007fffffff] usable
[    0.000000] BIOS-e820: [mem 0x00000000f0000000-0x00000000f7ffffff] reserved
[    0.000000] BIOS-e820: [mem 0x00000000fec00000-0x00000000fec0ffff] reserved
[    0.000000] BIOS-e820: [mem 0x00000000fee00000-0x00000000fee00fff] reserved
:

enable

enable 命令用于启动或关闭 shell 内建指令,若要执行的文件名称与 shell 内建指令相同,可用 enable -n 来关闭 shell 内建指令。若不加 -n 参数,enable可重新启动关闭的指令。

参数说明

  • -n  关闭指定的shell内建指令。
  • -all  显示shell所有关闭与启动的指令。

enable

[root@master shell_learning]# enable
enable .
enable :
enable [
enable alias
enable bg
enable bind
enable break
enable builtin
enable caller
enable cd
enable command
...

eval

eval 命令用于重新运算求出参数的内容。eval 可读取一连串的参数,然后再依参数本身的特性来执行。

eval echo "hello world"; ls

[root@master shell_learning]# eval echo "hello world"; ls
hello world
test_dir  test.sh  test.txt

export

export 命令用于设置或显示环境变量。在 shell 中执行程序时,shell 会提供一组环境变量。export 可新增,修改或删除环境变量,供后续执行的程序使用。export 的效力仅限于该次登陆操作。

参数

  • -f  代表[变量名称]中为函数名称。
  • -n  删除指定的变量。变量实际上并未删除,只是不会输出到后续指令的执行环境中。
  • -p  列出所有的shell赋予程序的环境变量。

export -p

列出当前的环境变量。

[root@master shell_learning]# export -p
declare -x HISTCONTROL="ignoredups"
declare -x HISTSIZE="1000"
declare -x HOME="/root"
declare -x HOSTNAME="master"
declare -x LANG="en_US.UTF-8"
declare -x LESSOPEN="||/usr/bin/lesspipe.sh %s"
declare -x LOGNAME="root"

export MYENV

定义环境变量。 

[root@master shell_learning]# export MYENV
[root@master shell_learning]# export -p
declare -x HISTCONTROL="ignoredups"
declare -x HISTSIZE="1000"
declare -x HOME="/root"
declare -x HOSTNAME="master"
declare -x LANG="en_US.UTF-8"
declare -x LESSOPEN="||/usr/bin/lesspipe.sh %s"
declare -x LOGNAME="root"
declare -x MAIL="/var/spool/mail/root"
declare -x MYENV
...

export MYENV=7

定义环境变量并赋值。 

[root@master shell_learning]# export MYENV=7
[root@master shell_learning]# export -p
declare -x HISTCONTROL="ignoredups"
declare -x HISTSIZE="1000"
declare -x HOME="/root"
declare -x HOSTNAME="master"
declare -x LANG="en_US.UTF-8"
declare -x LESSOPEN="||/usr/bin/lesspipe.sh %s"
declare -x LOGNAME="root"
declare -x MAIL="/var/spool/mail/root"
declare -x MYENV="7"

export -n MYENV

删除指定环境变量。 

[root@master shell_learning]# export -n MYENV

lsmod

lsmod(英文全拼:list modules)命令用于显示已载入系统的模块。执行 lsmod 指令,会列出所有已载入系统的模块。Linux 操作系统的核心具有模块化的特性,应此在编译核心时,务须把全部的功能都放入核心。您可以将这些功能编译成一个个单独的模块,待需要时再分别载入。

[root@master shell_learning]# lsmod
Module                  Size  Used by
ip6t_rpfilter          12595  1 
ipt_REJECT             12541  2 
nf_reject_ipv4         13373  1 ipt_REJECT
ip6t_REJECT            12625  2 
nf_reject_ipv6         13717  1 ip6t_REJECT
xt_conntrack           12760  11 
ip_set                 45644  0 
...

passwd

passwd 命令用来更改使用者的密码。

参数

  • -d 删除密码
  • -f 强迫用户下次登录时必须修改口令
  • -w 口令要到期提前警告的天数
  • -k 更新只能发送在过期之后
  • -l 停止账号使用
  • -S 显示密码信息
  • -u 启用已被停止的账户
  • -x 指定口令最长存活期
  • -g 修改群组密码
  • 指定口令最短存活期
  • -i 口令过期后多少天停用账户

 passwd

[looking@master ~]$ passwd
Changing password for user looking.
Changing password for looking.
(current) UNIX password: 

^C

passwd looking

root 不需要输入原密码即可设置其他用户密码。 

[root@master shell_learning]# passwd looking
Changing password for user looking.
New password: 

 passwd -S looking

显示账号密码信息

[root@master shell_learning]# passwd -S looking
looking PS 2020-10-10 0 99999 7 -1 (Password set, SHA512 crypt.)

passwd -d looking 

删除账号密码

[root@master shell_learning]# passwd -d looking
Removing password for user looking.
passwd: Success

set

set 命令用于设置 shell。set 指令能设置所使用 shell 的执行方式,可依照不同的需求来做设置。

参数

  • -a  标示已修改的变量,以供输出至环境变量。
  • -b  使被中止的后台程序立刻回报执行状态。
  • -C  转向所产生的文件无法覆盖已存在的文件。
  • -d  Shell预设会用杂凑表记忆使用过的指令,以加速指令的执行。使用-d参数可取消。
  • -e  若指令传回值不等于0,则立即退出shell。
  • -f   取消使用通配符。
  • -h  自动记录函数的所在位置。
  • -H Shell  可利用"!"加<指令编号>的方式来执行history中记录的指令。
  • -k  指令所给的参数都会被视为此指令的环境变量。
  • -l  记录for循环的变量名称。
  • -m  使用监视模式。
  • -n  只读取指令,而不实际执行。
  • -p  启动优先顺序模式。
  • -P  启动-P参数后,执行指令时,会以实际的文件或目录来取代符号连接。
  • -t  执行完随后的指令,即退出shell。
  • -u  当执行时使用到未定义过的变量,则显示错误信息。
  • -v  显示shell所读取的输入值。
  • -x  执行指令后,会先显示该指令及所下的参数。
  • +<参数>  取消某个set曾启动的参数。

set

[root@master shell_learning]# set
BASH=/usr/bin/bash
BASHOPTS=checkwinsize:cmdhist:expand_aliases:extquote:force_fignore:histappend:hostcomplete:interactive_comments:progcomp:promptvars:sourcepath
BASH_ALIASES=()
BASH_ARGC=()
BASH_ARGV=()
BASH_CMDS=()
BASH_LINENO=()
BASH_SOURCE=()
...

unset

unset 命令用于删除变量或函数。unset 为 shell 内建指令,可删除变量或函数。

参数

  • -f  仅删除函数。
  • -v  仅删除变量。

unset MYENV

同 export -n MYENV

[root@master shell_learning]# unset MYENV

ulimit

ulimit 命令用于控制 shell 程序的资源。ulimit 为 shell 内建指令,可用来控制shell执行程序的资源。

参数

  • -a  显示目前资源限制的设定。
  • -c  设定core文件的最大值,单位为区块。
  • -d <数据节区大小>  程序数据节区的最大值,单位为KB。
  • -f <文件大小>  shell所能建立的最大文件,单位为区块。
  • -H  设定资源的硬性限制,也就是管理员所设下的限制。
  • -m <内存大小>  指定可使用内存的上限,单位为KB。
  • -n <文件数目>  指定同一时间最多可开启的文件数。
  • -p <缓冲区大小>  指定管道缓冲区的大小,单位512字节。
  • -s <堆叠大小>  指定堆叠的上限,单位为KB。
  • -S  设定资源的弹性限制。
  • -t  指定CPU使用时间的上限,单位为秒。
  • -u <程序数目>  用户最多可开启的程序数目。
  • -v <虚拟内存大小>  指定可使用的虚拟内存上限,单位为KB。

ulimit -a

显示系统资源的设置 。

[root@master shell_learning]# ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 7183
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 7183
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

ulimit -u 500 

设置单一用户程序数目上限。

[root@master shell_learning]# ulimit -u 500

备份压缩

ar

ar 命令用于建立或修改备存文件,或是从备存文件中抽取文件。ar 可让您集合许多文件,成为单一的备存文件。在备存文件中,所有成员文件皆保有原来的属性与权限。

必要参数

  • -d  删除备存文件中的成员文件。
  • -m  变更成员文件在备存文件中的次序。
  • -p  显示备存文件中的成员文件内容。
  • -q  将文件附加在备存文件末端。
  • -r  将文件插入备存文件中。
  • -t  显示备存文件中所包含的文件。
  • -x    自备存文件中取出成员文件。

选项参数

  • a<成员文件>  将文件插入备存文件中指定的成员文件之后。
  • b<成员文件>  将文件插入备存文件中指定的成员文件之前。
  • c  建立备存文件。
  • f  为避免过长的文件名不兼容于其他系统的ar指令指令,因此可利用此参数,截掉要放入备存文件中过长的成员文件名称。
  • i<成员文件>  将文件插入备存文件中指定的成员文件之前。
  • o  保留备存文件中文件的日期。
  • s  若备存文件中包含了对象模式,可利用此参数建立备存文件的符号表。
  • S  不产生符号表。
  • u  只将日期较新文件插入备存文件中。
  • v  程序执行时显示详细的信息。
  • V  显示版本信息。

ar -rv one.bak test.sh test.txt

打包文件。

[root@master shell_learning]# ar -rv one.bak test.sh test.txt
ar: creating one.bak
a - test.sh
a - test.txt

ar -rv two.bak test.*

打包多个文件。 

[root@master shell_learning]# ar -rv two.bak test.*
ar: creating two.bak
a - test.sh
a - test.txt

ar -t two.bak

显示打包文件内容。

[root@master shell_learning]# ar -t two.bak
test.sh
test.txt

ar -d two.bak test.sh

删除打包文件成员文件。 

[root@master shell_learning]# ar -t two.bak
test.sh
test.txt
[root@master shell_learning]# ar -d two.bak test.sh
[root@master shell_learning]# ar -t two.bak
test.txt

bzip2

Linux bzip/bunzip2命令是.bz2文件的解压缩程序。

bunzip2 可解压缩.bz2格式的压缩文件。bunzip2 实际上是 bzip2 的符号连接,执行 bunzip2 与 bzip2 -d 的效果相同。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

usage: bzip2 [flags and input files in any order]

-h --help           print this message

-d --decompress     force decompression

-z --compress       force compression

-k --keep           keep (don't delete) input files

-f --force          overwrite existing output files

-t --test           test compressed file integrity

-c --stdout         output to standard out

-q --quiet          suppress noncritical error messages

-v --verbose        be verbose (a 2nd -v gives more)

-L --license        display software version & license

-V --version        display software version & license

-s --small          use less memory (at most 2500k)

-1 .. -9            set block size to 100k .. 900k

--fast              alias for -1

--best              alias for –9

[root@localhost ~]# bzip2 -d filelists.sqlite.bz2 

gzip

gzip 是个使用广泛的压缩程序,文件经它压缩过后,其名称后面会多出".gz"的扩展名。

参数

  • -a或--ascii  使用ASCII文字模式。
  • -c或--stdout或--to-stdout  把压缩后的文件输出到标准输出设备,不去更动原始文件。
  • -d或--decompress或----uncompress  解开压缩文件。
  • -f或--force  强行压缩文件。不理会文件名称或硬连接是否存在以及该文件是否为符号连接。
  • -h或--help  在线帮助。
  • -l或--list  列出压缩文件的相关信息。
  • -L或--license  显示版本与版权信息。
  • -n或--no-name  压缩文件时,不保存原来的文件名称及时间戳记。
  • -N或--name  压缩文件时,保存原来的文件名称及时间戳记。
  • -q或--quiet  不显示警告信息。
  • -r或--recursive  递归处理,将指定目录下的所有文件及子目录一并处理。
  • -S<压缩字尾字符串>或----suffix<压缩字尾字符串>  更改压缩字尾字符串。
  • -t或--test  测试压缩文件是否正确无误。
  • -v或--verbose  显示指令执行过程。
  • -V或--version  显示版本信息。
  • -<压缩效率>  压缩效率是一个介于1-9的数值,预设值为"6",指定愈大的数值,压缩效率就会愈高。
  • --best  此参数的效果和指定"-9"参数相同。
  • --fast  此参数的效果和指定"-1"参数相同。

gzip *

压缩文件

[root@master shell_learning]# ls
test_dir  test.sh  test.txt
[root@master shell_learning]# gzip *
gzip: test_dir is a directory -- ignored
[root@master shell_learning]# ls
test_dir  test.sh.gz  test.txt.gz

gzip -l *

显示压缩文件信息 

[root@master shell_learning]# ls
test_dir  test.sh.gz  test.txt.gz
[root@master shell_learning]# gzip -l *
gzip: test_dir is a directory -- ignored
         compressed        uncompressed  ratio uncompressed_name
                 28                   0   0.0% test.sh
                 29                   0   0.0% test.txt
[root@master shell_learning]# ls
test_dir  test.sh.gz  test.txt.gz

gzip -dv * 

解压并列出详细信息

[root@master shell_learning]# ls
test_dir  test.sh.gz  test.txt.gz
[root@master shell_learning]# gzip -dv *
gzip: test_dir is a directory -- ignored
test.sh.gz:	  0.0% -- replaced with test.sh
test.txt.gz:	  0.0% -- replaced with test.txt
[root@master shell_learning]# ls
test_dir  test.sh  test.txt

tar

tar 是用来建立,还原备份文件的工具程序,它可以加入,解开备份文件内的文件。

参数

  • -A或--catenate 新增文件到已存在的备份文件。
  • -b<区块数目>或--blocking-factor=<区块数目> 设置每笔记录的区块数目,每个区块大小为12Bytes。
  • -B或--read-full-records 读取数据时重设区块大小。
  • -c或--create 建立新的备份文件。
  • -C<目的目录>或--directory=<目的目录> 切换到指定的目录。
  • -d或--diff或--compare 对比备份文件内和文件系统上的文件的差异。
  • -f<备份文件>或--file=<备份文件> 指定备份文件。
  • -F
  • -g或--listed-incremental 处理GNU格式的大量备份。
  • -G或--incremental 处理旧的GNU格式的大量备份。
  • -h或--dereference 不建立符号连接,直接复制该连接所指向的原始文件。
  • -i或--ignore-zeros 忽略备份文件中的0 Byte区块,也就是EOF。
  • -k或--keep-old-files 解开备份文件时,不覆盖已有的文件。
  • -K<文件>或--starting-file=<文件> 从指定的文件开始还原。
  • -l或--one-file-system 复制的文件或目录存放的文件系统,必须与tar指令执行时所处的文件系统相同,否则不予复制。
  • -L<媒体容量>或-tape-length=<媒体容量> 设置存放每体的容量,单位以1024 Bytes计算。
  • -m或--modification-time 还原文件时,不变更文件的更改时间。
  • -M或--multi-volume 在建立,还原备份文件或列出其中的内容时,采用多卷册模式。
  • -N<日期格式>或--newer=<日期时间> 只将较指定日期更新的文件保存到备份文件里。
  • -o或--old-archive或--portability 将资料写入备份文件时使用V7格式。
  • -O或--stdout 把从备份文件里还原的文件输出到标准输出设备。
  • -p或--same-permissions 用原来的文件权限还原文件。
  • -P或--absolute-names 文件名使用绝对名称,不移除文件名称前的"/"号。
  • -r或--append 新增文件到已存在的备份文件的结尾部分。
  • -R或--block-number 列出每个信息在备份文件中的区块编号。
  • -s或--same-order 还原文件的顺序和备份文件内的存放顺序相同。
  • -S或--sparse 倘若一个文件内含大量的连续0字节,则将此文件存成稀疏文件。
  • -t或--list 列出备份文件的内容。
  • -T<范本文件>或--files-from=<范本文件> 指定范本文件,其内含有一个或多个范本样式,让tar解开或建立符合设置条件的文件。
  • -u或--update 仅置换较备份文件内的文件更新的文件。
  • -U或--unlink-first 解开压缩文件还原文件之前,先解除文件的连接。
  • -v或--verbose 显示指令执行过程。
  • -V<卷册名称>或--label=<卷册名称> 建立使用指定的卷册名称的备份文件。
  • -w或--interactive 遭遇问题时先询问用户。
  • -W或--verify 写入备份文件后,确认文件正确无误。
  • -x或--extract或--get 从备份文件中还原文件。
  • -X<范本文件>或--exclude-from=<范本文件> 指定范本文件,其内含有一个或多个范本样式,让ar排除符合设置条件的文件。
  • -z或--gzip或--ungzip 通过gzip指令处理备份文件。
  • -Z或--compress或--uncompress 通过compress指令处理备份文件。
  • -<设备编号><存储密度> 设置备份用的外围设备编号及存放数据的密度。
  • --after-date=<日期时间> 此参数的效果和指定"-N"参数相同。
  • --atime-preserve 不变更文件的存取时间。
  • --backup=<备份方式>或--backup 移除文件前先进行备份。
  • --checkpoint 读取备份文件时列出目录名称。
  • --concatenate 此参数的效果和指定"-A"参数相同。
  • --confirmation 此参数的效果和指定"-w"参数相同。
  • --delete 从备份文件中删除指定的文件。
  • --exclude=<范本样式> 排除符合范本样式的文件。
  • --group=<群组名称> 把加入设备文件中的文件的所属群组设成指定的群组。
  • --help 在线帮助。
  • --ignore-failed-read 忽略数据读取错误,不中断程序的执行。
  • --new-volume-script=
  • --newer-mtime 只保存更改过的文件。
  • --no-recursion 不做递归处理,也就是指定目录下的所有文件及子目录不予处理。
  • --null 从null设备读取文件名称。
  • --numeric-owner 以用户识别码及群组识别码取代用户名称和群组名称。
  • --owner=<用户名称> 把加入备份文件中的文件的拥有者设成指定的用户。
  • --posix 将数据写入备份文件时使用POSIX格式。
  • --preserve 此参数的效果和指定"-ps"参数相同。
  • --preserve-order 此参数的效果和指定"-A"参数相同。
  • --preserve-permissions 此参数的效果和指定"-p"参数相同。
  • --record-size=<区块数目> 此参数的效果和指定"-b"参数相同。
  • --recursive-unlink 解开压缩文件还原目录之前,先解除整个目录下所有文件的连接。
  • --remove-files 文件加入备份文件后,就将其删除。
  • --rsh-command=<执行指令> 设置要在远端主机上执行的指令,以取代rsh指令。
  • --same-owner 尝试以相同的文件拥有者还原文件。
  • --suffix=<备份字尾字符串> 移除文件前先行备份。
  • --totals 备份文件建立后,列出文件大小。
  • --use-compress-program=<执行指令> 通过指定的指令处理备份文件。
  • --version 显示版本信息。
  • --volno-file=<编号文件> 使用指定文件内的编号取代预设的卷册编号。

tar -czvf test.tar.gz test.sh

压缩文件。

[root@master shell_learning]# ls
GitTest-1.1.tar.gz  test_dir  test.sh  test.txt
[root@master shell_learning]# tar -czvf test.tar.gz test.sh
test.sh
[root@master shell_learning]# ls
GitTest-1.1.tar.gz  test_dir  test.sh  test.tar.gz  test.txt

tar -xzvf GitTest-1.1.tar.gz (常用)

解压文件。

[root@master shell_learning]# ls
GitTest-1.1.tar.gz  test_dir  test.sh  test.txt
[root@master shell_learning]# tar -xzvf GitTest-1.1.tar.gz 
GitTest-1.1/
GitTest-1.1/b.txt
GitTest-1.1/hello.txt
GitTest-1.1/looking.txt
GitTest-1.1/myGit.txt
GitTest-1.1/newBranch.txt
GitTest-1.1/readme.txt
GitTest-1.1/test.txt
GitTest-1.1/world.txt
[root@master shell_learning]# ls
GitTest-1.1  GitTest-1.1.tar.gz  test_dir  test.sh  test.txt

tar -tzvf GitTest-1.1.tar.gz  

列出压缩文件内容。

[root@master shell_learning]# ls
GitTest-1.1.tar.gz  test_dir  test.sh  test.txt
[root@master shell_learning]# tar -tzvf GitTest-1.1.tar.gz 
drwxrwxr-x root/root         0 2019-06-05 14:11 GitTest-1.1/
-rw-rw-r-- root/root        32 2019-06-05 14:11 GitTest-1.1/b.txt
-rw-rw-r-- root/root        12 2019-06-05 14:11 GitTest-1.1/hello.txt
-rw-rw-r-- root/root         0 2019-06-05 14:11 GitTest-1.1/looking.txt
-rw-rw-r-- root/root        19 2019-06-05 14:11 GitTest-1.1/myGit.txt
-rw-rw-r-- root/root         0 2019-06-05 14:11 GitTest-1.1/newBranch.txt
-rw-rw-r-- root/root        45 2019-06-05 14:11 GitTest-1.1/readme.txt
-rw-rw-r-- root/root        13 2019-06-05 14:11 GitTest-1.1/test.txt
-rw-rw-r-- root/root        47 2019-06-05 14:11 GitTest-1.1/world.txt
[root@master shell_learning]# ls
GitTest-1.1.tar.gz  test_dir  test.sh  test.txt

unzip

unzip为 .zip 压缩文件的解压缩程序。

参数

  • -c 将解压缩的结果显示到屏幕上,并对字符做适当的转换。
  • -f 更新现有的文件。
  • -l 显示压缩文件内所包含的文件。
  • -p 与-c参数类似,会将解压缩的结果显示到屏幕上,但不会执行任何的转换。
  • -t 检查压缩文件是否正确。
  • -u 与-f参数类似,但是除了更新现有的文件外,也会将压缩文件中的其他文件解压缩到目录中。
  • -v 执行是时显示详细的信息。
  • -z 仅显示压缩文件的备注文字。
  • -a 对文本文件进行必要的字符转换。
  • -b 不要对文本文件进行字符转换。
  • -C 压缩文件中的文件名称区分大小写。
  • -j 不处理压缩文件中原有的目录路径。
  • -L 将压缩文件中的全部文件名改为小写。
  • -M 将输出结果送到more程序处理。
  • -n 解压缩时不要覆盖原有的文件。
  • -o 不必先询问用户,unzip执行后覆盖原有文件。
  • -P<密码> 使用zip的密码选项。
  • -q 执行时不显示任何信息。
  • -s 将文件名中的空白字符转换为底线字符。
  • -V 保留VMS的文件版本信息。
  • -X 解压缩时同时回存文件原来的UID/GID。
  • [.zip文件] 指定.zip压缩文件。
  • [文件] 指定要处理.zip压缩文件中的哪些文件。
  • -d<目录> 指定文件解压缩后所要存储的目录。
  • -x<文件> 指定不要处理.zip压缩文件中的哪些文件。
  • -Z unzip -Z等于执行zipinfo指令。

unzip -l GitTest-1.1.zip 

查看压缩文件包含的文件。

[root@master shell_learning]# unzip -l GitTest-1.1.zip 
Archive:  GitTest-1.1.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  10-13-2020 17:21   GitTest-1.1/
       32  06-05-2019 14:11   GitTest-1.1/b.txt
       12  06-05-2019 14:11   GitTest-1.1/hello.txt
        0  06-05-2019 14:11   GitTest-1.1/looking.txt
       19  06-05-2019 14:11   GitTest-1.1/myGit.txt
        0  06-05-2019 14:11   GitTest-1.1/newBranch.txt
       45  06-05-2019 14:11   GitTest-1.1/readme.txt
       13  06-05-2019 14:11   GitTest-1.1/test.txt
       47  06-05-2019 14:11   GitTest-1.1/world.txt
---------                     -------
      168                     9 files

unzip -v GitTest-1.1.zip  

查看压缩文件目录信息。

[root@master shell_learning]# unzip -v GitTest-1.1.zip 
Archive:  GitTest-1.1.zip
 Length   Method    Size  Cmpr    Date    Time   CRC-32   Name
--------  ------  ------- ---- ---------- ----- --------  ----
       0  Stored        0   0% 10-13-2020 17:21 00000000  GitTest-1.1/
      32  Defl:N       14  56% 06-05-2019 14:11 426fbabb  GitTest-1.1/b.txt
      12  Defl:N       14 -17% 06-05-2019 14:11 af083b2d  GitTest-1.1/hello.txt
       0  Stored        0   0% 06-05-2019 14:11 00000000  GitTest-1.1/looking.txt
      19  Defl:N       18   5% 06-05-2019 14:11 ec4ecb6a  GitTest-1.1/myGit.txt
       0  Stored        0   0% 06-05-2019 14:11 00000000  GitTest-1.1/newBranch.txt
      45  Defl:N       19  58% 06-05-2019 14:11 160f9d83  GitTest-1.1/readme.txt
      13  Defl:N       15 -15% 06-05-2019 14:11 391b7a54  GitTest-1.1/test.txt
      47  Defl:N       43   9% 06-05-2019 14:11 4db99af2  GitTest-1.1/world.txt
--------          -------  ---                            -------
     168              123  27%                            9 files

unzip GitTest-1.1.zip 

解压文件。 

[root@master shell_learning]# ls
GitTest-1.1.zip  test_dir  test.sh  test.txt
[root@master shell_learning]# unzip GitTest-1.1.zip 
Archive:  GitTest-1.1.zip
   creating: GitTest-1.1/
  inflating: GitTest-1.1/b.txt       
  inflating: GitTest-1.1/hello.txt   
 extracting: GitTest-1.1/looking.txt  
  inflating: GitTest-1.1/myGit.txt   
 extracting: GitTest-1.1/newBranch.txt  
  inflating: GitTest-1.1/readme.txt  
  inflating: GitTest-1.1/test.txt    
  inflating: GitTest-1.1/world.txt   
[root@master shell_learning]# ls
GitTest-1.1  GitTest-1.1.zip  test_dir  test.sh  test.txt

zip

zip 是个使用广泛的压缩程序,压缩后的文件后缀名为 .zip。

参数

  • -A 调整可执行的自动解压缩文件。
  • -b<工作目录> 指定暂时存放文件的目录。
  • -c 替每个被压缩的文件加上注释。
  • -d 从压缩文件内删除指定的文件。
  • -D 压缩文件内不建立目录名称。
  • -f 更新现有的文件。
  • -F 尝试修复已损坏的压缩文件。
  • -g 将文件压缩后附加在既有的压缩文件之后,而非另行建立新的压缩文件。
  • -h 在线帮助。
  • -i<范本样式> 只压缩符合条件的文件。
  • -j 只保存文件名称及其内容,而不存放任何目录名称。
  • -J 删除压缩文件前面不必要的数据。
  • -k 使用MS-DOS兼容格式的文件名称。
  • -l 压缩文件时,把LF字符置换成LF+CR字符。
  • -ll 压缩文件时,把LF+CR字符置换成LF字符。
  • -L 显示版权信息。
  • -m 将文件压缩并加入压缩文件后,删除原始文件,即把文件移到压缩文件中。
  • -n<字尾字符串> 不压缩具有特定字尾字符串的文件。
  • -o 以压缩文件内拥有最新更改时间的文件为准,将压缩文件的更改时间设成和该文件相同。
  • -q 不显示指令执行过程。
  • -r 递归处理,将指定目录下的所有文件和子目录一并处理。
  • -S 包含系统和隐藏文件。
  • -t<日期时间> 把压缩文件的日期设成指定的日期。
  • -T 检查备份文件内的每个文件是否正确无误。
  • -u 与 -f 参数类似,但是除了更新现有的文件外,也会将压缩文件中的其他文件解压缩到目录中。
  • -v 显示指令执行过程或显示版本信息。
  • -V 保存VMS操作系统的文件属性。
  • -w 在文件名称里假如版本编号,本参数仅在VMS操作系统下有效。
  • -x<范本样式> 压缩时排除符合条件的文件。
  • -X 不保存额外的文件属性。
  • -y 直接保存符号连接,而非该连接所指向的文件,本参数仅在UNIX之类的系统下有效。
  • -z 替压缩文件加上注释。
  • -$ 保存第一个被压缩文件所在磁盘的卷册名称。
  • -<压缩效率> 压缩效率是一个介于1-9的数值。

zip -qr test_dir.zip ./test_dir/

压缩指定目录下的文件。

[root@master shell_learning]# ls
GitTest-1.1  GitTest-1.1.zip  test_dir  test.sh  test.txt
[root@master shell_learning]# zip -qr test_dir.zip ./test_dir/
[root@master shell_learning]# ls
GitTest-1.1  GitTest-1.1.zip  test_dir  test_dir.zip  test.sh  test.txt

zip -qr test_dir.zip *

压缩当前目录下的文件。 

[root@master test_dir]# ls
a.txt  b.txt
[root@master test_dir]# zip -qr test.zip *
[root@master test_dir]# ls
a.txt  b.txt  test.zip

zip -dv test.zip a.txt

从压缩文件中删除文件。 

[root@master test_dir]# zip -dv test.zip a.txt
1>1: updating: a.txt (stored 0%)
[root@master test_dir]# zip -dv test.zip adf.txt
	zip warning: name not matched: adf.txt

zip error: Nothing to do! (test.zip)

zipinfo

zipinfo 命令用于列出压缩文件信息。执行 zipinfo 指令可得知 zip 压缩文件的详细信息。

参数

  • -1 只列出文件名称。
  • -2 此参数的效果和指定"-1"参数类似,但可搭配"-h","-t"和"-z"参数使用。
  • -h 只列出压缩文件的文件名称。
  • -l 此参数的效果和指定"-m"参数类似,但会列出原始文件的大小而非每个文件的压缩率。
  • -m 此参数的效果和指定"-s"参数类似,但多会列出每个文件的压缩率。
  • -M 若信息内容超过一个画面,则采用类似more指令的方式列出信息。
  • -s 用类似执行"ls -l"指令的效果列出压缩文件内容。
  • -t 只列出压缩文件内所包含的文件数目,压缩前后的文件大小及压缩率。
  • -T 将压缩文件内每个文件的日期时间用年,月,日,时,分,秒的顺序列出。
  • -v 详细显示压缩文件内每一个文件的信息。
  • -x<范本样式> 不列出符合条件的文件的信息。
  • -z 如果压缩文件内含有注释,就将注释显示出来。

zipinfo -v test.zip 

[root@master test_dir]# zipinfo -v test.zip
Archive:  test.zip
There is no zipfile comment.

End-of-central-directory record:
-------------------------------

  Zip archive file size:                       298 (000000000000012Ah)
  Actual end-cent-dir record offset:           276 (0000000000000114h)
  Expected end-cent-dir record offset:         276 (0000000000000114h)
  (based on the length of the central directory and its expected offset)

  This zipfile constitutes the sole disk of a single-part archive; its
  central directory contains 2 entries.
  The central directory is 150 (0000000000000096h) bytes long,
  and its (expected) offset in bytes from the beginning of the zipfile
  is 126 (000000000000007Eh).


Central directory entry #1:
---------------------------

  a.txt

  offset of local header from start of archive:   0
                                                  (0000000000000000h) bytes
  file system or operating system of origin:      Unix
  version of encoding software:                   3.0
  minimum file system compatibility required:     MS-DOS, OS/2 or NT FAT
  minimum software version required to extract:   1.0
  compression method:                             none (stored)
  file security status:                           not encrypted
  extended local header:                          no
  file last modified on (DOS date/time):          2020 Oct 13 17:31:58
  file last modified on (UT extra field modtime): 2020 Oct 13 17:31:57 local
  file last modified on (UT extra field modtime): 2020 Oct 13 09:31:57 UTC
  32-bit CRC value (hex):                         00000000
  compressed size:                                0 bytes
  uncompressed size:                              0 bytes
  length of filename:                             5 characters
  length of extra field:                          24 bytes
  length of file comment:                         0 characters
  disk number on which file begins:               disk 1
  apparent file type:                             binary
  Unix file attributes (100644 octal):            -rw-r--r--
  MS-DOS file attributes (00 hex):                none

  The central-directory extra field contains:
  - A subfield with ID 0x5455 (universal time) and 5 data bytes.
    The local extra field has UTC/GMT modification/access times.
  - A subfield with ID 0x7875 (Unix UID/GID (any size)) and 11 data bytes:
    01 04 00 00 00 00 04 00 00 00 00.

  There is no file comment.

Central directory entry #2:
---------------------------

  b.txt

  offset of local header from start of archive:   63
                                                  (000000000000003Fh) bytes
  file system or operating system of origin:      Unix
  version of encoding software:                   3.0
  minimum file system compatibility required:     MS-DOS, OS/2 or NT FAT
  minimum software version required to extract:   1.0
  compression method:                             none (stored)
  file security status:                           not encrypted
  extended local header:                          no
  file last modified on (DOS date/time):          2020 Oct 13 17:32:00
  file last modified on (UT extra field modtime): 2020 Oct 13 17:31:59 local
  file last modified on (UT extra field modtime): 2020 Oct 13 09:31:59 UTC
  32-bit CRC value (hex):                         00000000
  compressed size:                                0 bytes
  uncompressed size:                              0 bytes
  length of filename:                             5 characters
  length of extra field:                          24 bytes
  length of file comment:                         0 characters
  disk number on which file begins:               disk 1
  apparent file type:                             binary
  Unix file attributes (100644 octal):            -rw-r--r--
  MS-DOS file attributes (00 hex):                none

  The central-directory extra field contains:
  - A subfield with ID 0x5455 (universal time) and 5 data bytes.
    The local extra field has UTC/GMT modification/access times.
  - A subfield with ID 0x7875 (Unix UID/GID (any size)) and 11 data bytes:
    01 04 00 00 00 00 04 00 00 00 00.

  There is no file comment.

其他常用命令

bc

bc 命令是任意精度计算器语言,通常在 linux 下结合管道符 | 当计算器用。它类似基本的计算器,使用这个计算器可以做基本的数学运算。

常用的运算:

  • + 加法
  • - 减法
  • * 乘法
  • / 除法
  • ^ 指数
  • % 余数

参数:

  • -i:强制进入交互式模式;
  • -l:定义使用的标准数学库
  • ; -w:对POSIX bc的扩展给出警告信息;
  • -q:不打印正常的GNU bc环境信息;
  • -v:显示指令版本信息;
  • -h:显示指令的帮助信息。

bc

[root@master shell_learning]# bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
2+4
6
2+3*4
14
quit

echo "15+6" 

[root@master shell_learning]# echo "15+6"
15+6
[root@master shell_learning]# echo "15+6" | bc
21

echo 'scale=2; (3.777 - 1.4744)/2' | bc

[root@master shell_learning]# echo 'scale=2; (3.777 - 1.4744)/2' | bc
1.15

echo "ibase=2;101" | bc 

[root@master shell_learning]# echo "ibase=2;101" | bc
5

 echo "obase=10;ibase=2;1011" | bc

进制转换,obase 表示转换后的目标进制,ibase 表示当前需要转换的值的进制。

[root@master shell_learning]# echo "obase=10;ibase=2;1011" | bc
11
[root@master shell_learning]# echo "obase=2;ibase=10;11" | bc
1011

------------------------------------------------------------
[root@master shell_learning]# abc=192
[root@master shell_learning]# echo "obase=2;$abc" | bc
11000000

[root@master shell_learning]# cba=11000000
[root@master shell_learning]# echo $((2#$cba))
192

------------------------------------------------------------
[root@master shell_learning]# abc=192
[root@master shell_learning]# echo "obase=16;$abc" | bc
C0

[root@master shell_learning]# cba=C0
[root@master shell_learning]# echo $((2#$cba))
192

head

head 命令可用于查看文件的开头部分的内容,有一个常用的参数 -n 用于显示行数,默认为 10,即显示 10 行的内容。

参数:

  • -q 隐藏文件名
  • -v 显示文件名
  • -c<数目> 显示的字节数。
  • -n<行数> 显示的行数。

head notes.log 

默认显示文件前 10 行。

[root@master shell_learning]# head notes.log 
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
begin
  require_relative "lib/did_you_mean/version"
rescue LoadError # Fallback to load version file in ruby core repository
  require_relative "version"
end

Gem::Specification.new do |spec|

head -5 notes.log

显示文件前 5 行。 

[root@master shell_learning]# head -5 notes.log 
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
begin
  require_relative "lib/did_you_mean/version"

head -c 10 notes.log 

显示文件前 10 个字符

[root@master shell_learning]# head -c 10 notes.log 
# coding: 

ip

ip 命令与 ifconfig 命令类似,但比 ifconfig 命令更加强大,主要功能是用于显示或设置网络设备。ip 命令是 Linux 加强版的的网络配置工具,用于代替 ifconfig 命令。

常用对象的取值含义如下:

  • link:网络设备
  • address:设备上的协议(IP或IPv6)地址
  • addrlabel:协议地址选择的标签配置
  • route:路由表条目
  • rule:路由策略数据库中的规则

常用选项的取值含义如下:

  • -V:显示命令的版本信息;
  • -s:输出更详细的信息;
  • -f:强制使用指定的协议族;
  • -4:指定使用的网络层协议是IPv4协议;
  • -6:指定使用的网络层协议是IPv6协议;
  • -0:输出信息每条记录输出一行,即使内容较多也不换行显示;
  • -r:显示主机时,不使用IP地址,而使用主机的域名。
  • help 为该命令的帮助信息。

 ip

ip link show                     # 显示网络接口信息
ip link set eth0 up              # 开启网卡
ip link set eth0 down            # 关闭网卡
ip link set eth0 promisc on      # 开启网卡的混合模式
ip link set eth0 promisc offi    # 关闭网卡的混个模式
ip link set eth0 txqueuelen 1200 # 设置网卡队列长度
ip link set eth0 mtu 1400        # 设置网卡最大传输单元
ip addr show     # 显示网卡IP信息
ip addr add 192.168.0.1/24 dev eth0 # 设置eth0网卡IP地址192.168.0.1
ip addr del 192.168.0.1/24 dev eth0 # 删除eth0网卡IP地址

ip route show # 显示系统路由
ip route add default via 192.168.1.254   # 设置系统默认路由
ip route list                 # 查看路由信息
ip route add 192.168.4.0/24  via  192.168.0.254 dev eth0 # 设置192.168.4.0网段的网关为192.168.0.254,数据走eth0接口
ip route add default via  192.168.0.254  dev eth0        # 设置默认网关为192.168.0.254
ip route del 192.168.4.0/24   # 删除192.168.4.0网段的网关
ip route del default          # 删除默认路由
ip route delete 192.168.1.0/24 dev eth0 # 删除路由

ip link list

显示网络设备的运行状态。

[root@master shell_learning]# ip link list
1: lo:  mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: ens33:  mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
    link/ether 00:0c:29:c0:25:3a brd ff:ff:ff:ff:ff:ff

ip -s link list

显示网络设备的运行详细状态。

[root@master shell_learning]# ip -s link list
1: lo:  mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    RX: bytes  packets  errors  dropped overrun mcast   
    0          0        0       0       0       0       
    TX: bytes  packets  errors  dropped carrier collsns 
    0          0        0       0       0       0       
2: ens33:  mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
    link/ether 00:0c:29:c0:25:3a brd ff:ff:ff:ff:ff:ff
    RX: bytes  packets  errors  dropped overrun mcast   
    464163     5400     0       0       0       0       
    TX: bytes  packets  errors  dropped carrier collsns 
    451575     4159     0       0       0       0  

ip route list

显示核心路由表。

[root@master shell_learning]# ip route list
default via 192.168.128.2 dev ens33 proto static metric 100 
192.168.128.0/24 dev ens33 proto kernel scope link src 192.168.128.130 metric 100 

ip neigh list

显示邻居表。 

[root@master shell_learning]# ip neigh list
192.168.128.2 dev ens33 lladdr 00:50:56:f6:2e:0b STALE
192.168.128.1 dev ens33 lladdr 00:50:56:c0:00:08 DELAY

ip link | grep -E '^[0-9]' | awk -F: '{print $2}'

获取主机所有网络接口

[root@master shell_learning]# ip link | grep -E '^[0-9]' | awk -F: '{print $2}'
 lo
 ens33

killall

killall 用于杀死一个进程,与 kill 不同的是它会杀死指定名字的所有进程。kill 命令杀死指定进程 PID,需要配合 ps 使用,而 killall 直接对进程对名字进行操作,更加方便。

参数

  • -e | --exact : 进程需要和名字完全相符
  • -I | --ignore-case :忽略大小写
  • -g | --process-group :结束进程组
  • -i | --interactive :结束之前询问
  • -l | --list :列出所有的信号名称
  • -q | --quite :进程没有结束时,不输出任何信息
  • -r | --regexp :将进程名模式解释为扩展的正则表达式。
  • -s | --signal :发送指定信号
  • -u | --user :结束指定用户的进程
  • -v | --verbose :显示详细执行过程
  • -w | --wait :等待所有的进程都结束
  • -V |--version :显示版本信息
  • --help :显示帮助信息

killall -9 php-fpm

[root@master shell_learning]# killall -9 php-fpm   # 结束所有的 php-fpm 进程

pkill -9 php-fpm 

[root@master shell_learning]# pkill -9 php-fpm   # 结束所有的 php-fpm 进程

nohup

nohup 英文全称 no hang up(不挂起),用于在系统后台不挂断地运行命令,退出终端不会影响程序的运行。

nohup 命令,在默认情况下(非重定向时),会输出一个名叫 nohup.out 的文件到当前目录下,如果当前目录的 nohup.out 文件不可写,输出重定向到 $HOME/nohup.out 文件中。

参数:

Command:要执行的命令。

Arg:一些参数,可以指定输出文件。

&:让命令在后台执行,终端退出后命令仍旧执行。

nohup ./test.sh &

[root@master shell_learning]# cat test.sh
echo "appending output to nohup.out"
[root@master shell_learning]# chmod +x test.sh

[root@master shell_learning]# nohup ./test.sh &
[1] 8798
[root@master shell_learning]# nohup: ignoring input and appending output to ‘nohup.out’

[1]+  Done                    nohup ./test.sh
[root@master shell_learning]# cat nohup.out 
appending output to nohup.out

nohup ./test.sh > runoob.log 2>&1 & 

2>&1 解释:

将标准错误 2 重定向到标准输出 &1 ,标准输出 &1 再被重定向输入到 runoob.log 文件中。

  • 0 – stdin (standard input,标准输入)
  • 1 – stdout (standard output,标准输出)
  • 2 – stderr (standard error,标准错误输出)
[root@master shell_learning]# nohup ./test.sh > runoob.log 2>&1 &
[1] 8812

[root@master shell_learning]# ls
arg.txt      GitTest-1.1.zip  notes.log   sk.sh     test_dir.zip  test.txt
GitTest-1.1  nohup.out        runoob.log  test_dir  test.sh
[1]+  Done                    nohup ./test.sh > runoob.log 2>&1

[root@master shell_learning]# cat runoob.log 
nohup: ignoring input
appending output to nohup.out

scp

scp 命令用于 Linux 之间复制文件和目录。scp 是 secure copy 的缩写, scp 是 linux 系统下基于 ssh 登陆进行安全的远程文件拷贝命令。

scp [可选参数] file_source file_target 

参数:

  • -1: 强制scp命令使用协议ssh1
  • -2: 强制scp命令使用协议ssh2
  • -4: 强制scp命令只使用IPv4寻址
  • -6: 强制scp命令只使用IPv6寻址
  • -B: 使用批处理模式(传输过程中不询问传输口令或短语)
  • -C: 允许压缩。(将-C标志传递给ssh,从而打开压缩功能)
  • -p:保留原文件的修改时间,访问时间和访问权限。
  • -q: 不显示传输进度条。
  • -r: 递归复制整个目录。
  • -v:详细方式显示输出。scp和ssh(1)会显示出整个过程的调试信息。这些信息用于调试连接,验证和配置问题。
  • -c cipher: 以cipher将数据传输进行加密,这个选项将直接传递给ssh。
  • -F ssh_config: 指定一个替代的ssh配置文件,此参数直接传递给ssh。
  • -i identity_file: 从指定文件中读取传输时使用的密钥文件,此参数直接传递给ssh。
  • -l limit: 限定用户所能使用的带宽,以Kbit/s为单位。
  • -o ssh_option: 如果习惯于使用ssh_config(5)中的参数传递方式,
  • -P port:注意是大写的P, port是指定数据传输用到的端口号
  • -S program: 指定加密传输时所使用的程序。此程序必须能够理解ssh(1)的选项。

远程到本地

scp remote_username@remote_ip:remote_folder/remote_file local_file
scp remote_username@remote_ip:remote_file local_folder
scp -r remote_username@remote_ip:remote_folder local_folder
scp -r -P port remote_username@remote_ip:remote_folder local_folder

本地到远程

scp local_file remote_username@remote_ip:remote_folder 
scp local_file remote_username@remote_ip:remote_file 
scp -r local_folder remote_username@remote_ip:remote_folder
scp -r -P port local_folder remote_username@remote_ip:remote_folder

tail

tail 命令可用于查看文件的内容,有一个常用的参数 -f 常用于查阅正在改变的日志文件。tail -f filename 会把 filename 文件里的最尾部的内容显示在屏幕上,并且不断刷新,只要 filename 更新就可以看到最新的文件内容。

参数:

  • -f flush 循环读取
  • -q quiet 不显示处理信息
  • -v 显示详细的处理信息
  • -c<数目> 显示的字节数
  • -n<行数> 显示文件的尾部 n 行内容
  • --pid=PID 与-f合用,表示在进程ID,PID死掉之后结束
  • -q, --quiet, --silent 从不输出给出文件名的首部
  • -s, --sleep-interval=S 与-f合用,表示在每次反复的间隔休眠S秒

tail notes.log 

默认显示文件最后 10 行。

[root@master shell_learning]# tail notes.log 

  spec.files         = `git ls-files`.split($/).reject{|path| path.start_with?('evaluation/') }
  spec.test_files    = spec.files.grep(%r{^(test)/})
  spec.require_paths = ["lib"]

  spec.required_ruby_version = '>= 2.5.0'

  spec.add_development_dependency "rake"
end

tail -f notes.log

此命令显示 notes.log 文件的最后 10 行。当将某些行添加至 notes.log 文件时,tail 命令会继续显示这些行。 显示一直继续,直到您按下(Ctrl-C)组合键停止显示。 

[root@master shell_learning]# echo "hello world" >> notes.log 
[root@master shell_learning]# tail -f notes.log 

  spec.files         = `git ls-files`.split($/).reject{|path| path.start_with?('evaluation/') }
  spec.test_files    = spec.files.grep(%r{^(test)/})
  spec.require_paths = ["lib"]

  spec.required_ruby_version = '>= 2.5.0'

  spec.add_development_dependency "rake"
end

hello world

tail -5 notes.log

显示文件最后 5 行。

[root@master shell_learning]# tail -5 notes.log

  spec.add_development_dependency "rake"
end

hello world

tail -c 10 notes.log

显示文件最后 10 个字符。 

[root@master shell_learning]# tail -c 10 notes.log
llo world

xargs

xargs是给命令传递参数的一个过滤器,也是组合多个命令的一个工具。可以将管道或标准输入(stdin)数据转换成命令行参数,也能够从文件的输出中读取数据。也可以将单行或多行文本输入转换为其他格式,例如多行变单行,单行变多行。xargs 默认的命令是 echo,这意味着通过管道传递给 xargs 的输入将会包含换行和空白,不过通过 xargs 的处理,换行和空白将被空格取代。xargs 是一个强有力的命令,它能够捕获一个命令的输出,然后传递给另外一个命令。之所以能用到这个命令,关键是由于很多命令不支持 | 管道来传递参数,而日常工作中有有这个必要,所以就有了 xargs 命令,

xargs 一般是和管道一起使用。

命令格式:

somecommand |xargs -item  command

参数:

  • -a file 从文件中读入作为sdtin
  • -e flag ,注意有的时候可能会是-E,flag必须是一个以空格分隔的标志,当xargs分析到含有flag这个标志的时候就停止。
  • -p 当每次执行一个argument的时候询问一次用户。
  • -n num 后面加次数,表示命令在执行的时候一次用的argument的个数,默认是用所有的。
  • -t 表示先打印命令,然后再执行。
  • -i 或者是-I,这得看linux支持了,将xargs的每项名称,一般是一行一行赋值给 {},可以用 {} 代替。
  • -r no-run-if-empty 当xargs的输入为空的时候则停止xargs,不用再去执行了。
  • -s num 命令行的最大字符数,指的是 xargs 后面那个命令的最大命令行字符数。
  • -L num 从标准输入一次读取 num 行送给 command 命令。
  • -l 同 -L。
  • -d delim 分隔符,默认的xargs分隔符是回车,argument的分隔符是空格,这里修改的是xargs的分隔符。
  • -x exit的意思,主要是配合-s使用。。
  • -P 修改最大的进程数,默认是1,为0时候为as many as it can ,这个例子我没有想到,应该平时都用不到的吧。

cat test.txt | xargs

多行输入单行输出。

[root@master shell_learning]# cat test.txt
a b c d e f g
h i j k l m n
o p q
r s t
u v w x y z
[root@master shell_learning]# cat test.txt | xargs
a b c d e f g h i j k l m n o p q r s t u v w x y z

cat test.txt | xargs -n4

多行输入多行输出。

[root@master shell_learning]# cat test.txt
a b c d e f g
h i j k l m n
o p q
r s t
u v w x y z
[root@master shell_learning]# cat test.txt | xargs -n4
a b c d
e f g h
i j k l
m n o p
q r s t
u v w x
y z

echo "nameXnameXnameXname" | xargs -dX

自定义定界符。

[root@master shell_learning]# echo "nameXnameXnameXname" | xargs -dX
name name name name

[root@master shell_learning]# echo "nameXnameXnameXname" | xargs -dX -n2
name name
name name

cat arg.txt | xargs -I {} ./sk.sh hello {} world 

[root@master shell_learning]# 
[root@master shell_learning]# cat sk.sh
#!/bin/bash
#sk.sh命令内容,打印出所有参数。

echo $*

[root@master shell_learning]# cat arg.txt
aaa
bbb
ccc

[root@master shell_learning]# cat arg.txt | xargs -I {} ./sk.sh hello {} world
hello aaa world
hello bbb world
hello ccc world

find . -name '*.json' | xargs rm -rf

[root@master shell_learning]# find . -name '*.json' | xargs rm -rf

你可能感兴趣的:(Linux,Linux命令)