目 录CONTENT

文章目录

常用shell命令

简中仙
2020-01-06 / 0 评论 / 0 点赞 / 62 阅读 / 0 字 / 正在检测是否收录...
温馨提示:
本文最后更新于2023-10-07,若内容或图片失效,请留言反馈。 本文如有错误或者侵权的地方,欢迎您批评指正!

一、Linux命令概述

1、通用的linux命令行使用格式:

命令字 [选项] [参数]

2、辅助操作

Tab键:可以将输入的不完整命令字或文件、目录名自动补齐,按两次Tab键,系统将输出可用的名称列表。

反斜杠"":可以插入符号强制换行,在下一行出现的">"提示符后可以继续输入内容,作为上一行命令的延续。

Ctrl+U组合键:快速删除当前光标处之前的所有字符内容。

Ctrl+K组合键:快速删除从当前光标处到行尾的所有字符内容。

Ctrl+L组合键:快速清空当前屏幕中的显示内容,只在左上角显示命令提示符。

Ctrl+C组合键:取消当前命令行的编辑,并切换为新的一行命令提示符。

3、获得命令帮助

1、内部命令可以通过:help 命令

# help cd
cd: cd [-L|[-P [-e]]] [dir]
    Change the shell working directory.
    
    Change the current directory to DIR.  The default DIR is the value of the
    HOME shell variable.
    
    The variable CDPATH defines the search path for the directory containing
    DIR.  Alternative directory names in CDPATH are separated by a colon (:).
    A null directory name is the same as the current directory.  If DIR begins
    with a slash (/), then CDPATH is not used.
    
    If the directory is not found, and the shell option `cdable_vars' is set,
    the word is assumed to be  a variable name.  If that variable has a value,
    its value is used for DIR.
    
    Options:
        -L	force symbolic links to be followed
        -P	use the physical directory structure without following symbolic
    	links
        -e	if the -P option is supplied, and the current working directory
    	cannot be determined successfully, exit with a non-zero status
    
    The default is to follow symbolic links, as if `-L' were specified.
    
    Exit Status:
    Returns 0 if the directory is changed, and if $PWD is set successfully when
    -P is used; non-zero otherwise.

2、外部命令可以通过:命令 --help

# ls --help
用法:ls [选项]... [文件]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.

Mandatory arguments to long options are mandatory for short options too.
  -a, --all			不隐藏任何以. 开始的项目
  -A, --almost-all		列出除. 及.. 以外的任何项目
      --author			与-l 同时使用时列出每个文件的作者
  -b, --escape			以八进制溢出序列表示不可打印的字符
      --block-size=SIZE      scale sizes by SIZE before printing them; e.g.,
                               '--block-size=M' prints sizes in units of
                               1,048,576 bytes; see SIZE format below
  -B, --ignore-backups       do not list implied entries ending with ~
  -c                         with -lt: sort by, and show, ctime (time of last
                               modification of file status information);
                               with -l: show ctime and sort by name;
                               otherwise: sort by ctime, newest first
  -C                         list entries by columns
      --color[=WHEN]         colorize the output; WHEN can be 'never', 'auto',
                               or 'always' (the default); more info below
  -d, --directory            list directories themselves, not their contents
  -D, --dired                generate output designed for Emacs' dired mode
  -f                         do not sort, enable -aU, disable -ls --color
  -F, --classify             append indicator (one of */=>@|) to entries
      --file-type            likewise, except do not append '*'
      --format=WORD          across -x, commas -m, horizontal -x, long -l,
                               single-column -1, verbose -l, vertical -C
      --full-time            like -l --time-style=full-iso
  -g				类似-l,但不列出所有者
      --group-directories-first
                             group directories before files;
                               can be augmented with a --sort option, but any
                               use of --sort=none (-U) disables grouping
  -G, --no-group		以一个长列表的形式,不输出组名
  -h, --human-readable		与-l 一起,以易于阅读的格式输出文件大小
				(例如 1K 234M 2G)
      --si			同上面类似,但是使用1000 为基底而非1024
  -H, --dereference-command-line
                             follow symbolic links listed on the command line
      --dereference-command-line-symlink-to-dir
                             follow each command line symbolic link
                               that points to a directory
      --hide=PATTERN         do not list implied entries matching shell PATTERN
                               (overridden by -a or -A)
      --indicator-style=WORD  append indicator with style WORD to entry names:
                               none (default), slash (-p),
                               file-type (--file-type), classify (-F)
  -i, --inode                print the index number of each file
  -I, --ignore=PATTERN       do not list implied entries matching shell PATTERN
  -k, --kibibytes            default to 1024-byte blocks for disk usage
  -l				使用较长格式列出信息
  -L, --dereference		当显示符号链接的文件信息时,显示符号链接所指示
				的对象而并非符号链接本身的信息
  -m				所有项目以逗号分隔,并填满整行行宽
  -n, --numeric-uid-gid		类似 -l,但列出UID 及GID 号
  -N, --literal			输出未经处理的项目名称 (如不特别处理控制字符)
  -o				类似 -l,但不列出有关组的信息
  -p,  --indicator-style=slash	对目录加上表示符号"/"
  -q, --hide-control-chars   print ? instead of nongraphic characters
      --show-control-chars   show nongraphic characters as-is (the default,
                               unless program is 'ls' and output is a terminal)
  -Q, --quote-name           enclose entry names in double quotes
      --quoting-style=WORD   use quoting style WORD for entry names:
                               literal, locale, shell, shell-always, c, escape
  -r, --reverse			逆序排列
  -R, --recursive		递归显示子目录
  -s, --size			以块数形式显示每个文件分配的尺寸
  -S                         sort by file size
      --sort=WORD            sort by WORD instead of name: none (-U), size (-S),
                               time (-t), version (-v), extension (-X)
      --time=WORD            with -l, show time as WORD instead of default
                               modification time: atime or access or use (-u)
                               ctime or status (-c); also use specified time
                               as sort key if --sort=time
      --time-style=STYLE     with -l, show times using style STYLE:
                               full-iso, long-iso, iso, locale, or +FORMAT;
                               FORMAT is interpreted like in 'date'; if FORMAT
                               is FORMAT1<newline>FORMAT2, then FORMAT1 applies
                               to non-recent files and FORMAT2 to recent files;
                               if STYLE is prefixed with 'posix-', STYLE
                               takes effect only outside the POSIX locale
  -t                         sort by modification time, newest first
  -T, --tabsize=COLS         assume tab stops at each COLS instead of 8
  -u                         with -lt: sort by, and show, access time;
                               with -l: show access time and sort by name;
                               otherwise: sort by access time
  -U                         do not sort; list entries in directory order
  -v                         natural sort of (version) numbers within text
  -w, --width=COLS           assume screen width instead of current value
  -x                         list entries by lines instead of by columns
  -X                         sort alphabetically by entry extension
  -1                         list one file per line

SELinux options:

  --lcontext                 Display security context.   Enable -l. Lines
                             will probably be too wide for most displays.
  -Z, --context              Display security context so it fits on most
                             displays.  Displays only mode, user, group,
                             security context and file name.
  --scontext                 Display only security context and file name.
      --help		显示此帮助信息并退出
      --version		显示版本信息并退出

SIZE is an integer and optional unit (example: 10M is 10*1024*1024).  Units
are K, M, G, T, P, E, Z, Y (powers of 1024) or KB, MB, ... (powers of 1000).

使用色彩来区分文件类型的功能已被禁用,默认设置和 --color=never 同时禁用了它。
使用 --color=auto 选项,ls 只在标准输出被连至终端时才生成颜色代码。
LS_COLORS 环境变量可改变此设置,可使用 dircolors 命令来设置。


退出状态:
 0  正常
 1  一般问题 (例如:无法访问子文件夹)
 2  严重问题 (例如:无法使用命令行参数)

GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
请向<http://translationproject.org/team/zh_CN.html> 报告ls 的翻译错误
要获取完整文档,请运行:info coreutils 'ls invocation'

3、可以通过info命令获取命令帮助

# info cd
File: *manpages*,  Node: cd,  Up: (dir)

BASH(1)                     General Commands Manual                    BASH(1)



NAME
       bash - GNU Bourne-Again SHell (GNU 命令解释程序 “Bourne二世”)

概
       bash [options] [file]

版
       Bash is Copyright (C) 1989-2002 by the Free Software Foundation, Inc.

描
       Bash                             是一个与                            sh
       兼容的命令解释程序,可以执行从标准输入或者文件中读取的命令。       Bash
       也整合了 Korn 和 C Shell (ksh 和 csh) 中的优秀特性。

       Bash  的目标是成为遵循  IEEE  POSIX Shell and Tools specification (IEEE
       Working Group 1003.2,可移植操作系统规约: shell 和工具) 的实现。
-----Info: (*manpages*)cd, 5656 lines --Top-------------------------------------
Welcome to Info version 5.1. Type h for help, m for menu item.

4、使用man手册页

man手册页(Manual Page)是Linux操作系统中最为常用的一种在线帮助形式,绝大部分的外部 软件在安装时为执行程序、配置文件提供了详细的帮助手册页
查看rm命令的手册页信息

# man rm
RM(1)                       General Commands Manual                      RM(1)

NAME
       rm - 移除文件或者目录

总览
       rm [options"]file...

POSIX(Portable Operating System Interface 可移植的操作系统接口) 选项:
       [-fiRr]

GNU 选项 (最短格式):
       [-dfirvR][--help][--version][--]

描述
       rm移除每个给定的文件。默认情况下,它不能移除目录。但是当给定了-r或者-R选
       项时,在指定目录之下的整个目录树都会被移除(而且对通过`rm
       -r'能够移除的目
       录树深度是没有限制的)。当文件路径末端部分只有.和..时会出错(因此可用`rm
       -r .*'之类来避免这些不愉快的诧异)。

       如果给定了-i选项,或者如果一个文件不可写,
       而且标准输入是终端,又没有给定-f选项,那么rm会提
 Manual page rm(1) line 1 (press h for help or q to quit)

如果需要将man手册页的内容保存成文本文件以便在其他系统中查看,可以结合col命令去除手册页中的格式控制字符,并将显示结果保存为新的文件
将Is命令的帮助手 册保存为文本文件lshelp.txt

# man ls | col -b >lshelp.txt

管道:用竖杠符号|表示,用于将前面命令的屏幕输出结果作为后面命令的操作对象(输入)。

重定向输出:用大于符号">"表示,前面的命令成功执行以后,其屏幕输出结果将保存 到">"号后边指定的文件中,而不是直接输出到屏幕,因此称为重定向。

二、文件系统

1、系统目录

目录解释
rootfs()根文件系统 /
/boot系统启动相关的静态文件
/dev所有设备的设备文件,设备文件也称为特殊文件
/etc配置文件
/home普通用户的家目录,每一个用户的家目录通常默认为/home/USERNAME
/root管理员的家目录
/lib基本的共享库和内核模块
/media移动设备的挂载点目录
/mnt挂载点目录,额外的临时文件系统
/opt可选目录,第三方程序的安装目录
/proc内核及进程信息的虚拟文件系统,伪文件系统,内核映射文件,只存在内存中
/sys伪文件系统,硬件设备信息虚拟文件系统接口,跟硬件设备相关的属性映射文件
/tmp临时文件
/var可变化的文件(内容发生变化)/var/log 日志信息
/bin基础的用户命令二进制程序,为所有用户使用
/sbin系统二进制程序,一般为管理命令
/usr不适合放在/bin或/etc目录下的额外的工具

2、查看服务器基本信息

常用命令命令含义
cat /proc/cpuinfo查看cpu信息
cat /proc/meminfo查看内存信息
free查看内存使用情况
uptime监控CPU情况
cat /etc/redhat-release查看发行版信息
hostname查看主机名
ip addr查看ip信息
ifconfig查看ip信息
netstat查看网络连接信息、路由表等,常用来查看端口打开情况
fdisk -l查看硬盘信息
df查看设备挂载信息

更改主机名

# hostnamectl set-hostname node1
# bash

三、目录和文件基本操作

1、查看及切换目录

1、pwd命令:查看当前的工作目录

# pwd
/root

2、cd命令:切换工作目录

# cd          # 切换到用户主目录
# cd ~        # 切换到用户主目录
# cd -        # 切换到上一个工作目录
# cd ..       # 切换到上级目录
# cd ../..    # 切换到上两级目录

在Linux操作系统中表示某个目录(或文件)的位置时,根据其参照的起始目录不同,可以使用两种不同的形式,分别称为绝对路径和相对路径。

绝对路径:这种方式以根目录“/”作为起点

相对路径:这种方式一般以当前工作目录作为起点,在开头不使用"/"符号相对路径主要包括如下几种形式:

  • 直接使用目录名或文件名表示当前工作目录中的子目录、文件的位置。
  • 使用一个点号开头可明确表示以当前的工作目录作为起点。
  • 使用两个点号幵头表示以当前目录的上一级目录(父目录)作为起点。
  • 使用用户名"的形式开头表示以指定用户的宿主目录作为起点,省略用户名时默认为当前用户。

3、Is命令:列表显示目录内容

  • -I:以长格式显示文件和目录的列表,包括权限、大小、最后更新时间等详细信息。不使用-选项时,Is命令默认以短格式显示目录名或文件名信息。
  • -a:显示所有子目录和文件的信息,包括名称以点号开头的隐藏目录和隐藏文件。
  • -A:与-a选项的作用基本类似,但有两个特殊隐藏目录不会显示,即表示当前目录的"."和表示父目录的".."。
  • -d:显示目录本身的属性,而不是显示目录中的内容。
  • -h:以更人性化的方式显示目录或文件的大小,默认的大小单位为字节(B),使用-h选项后将显示为KB、MB等单位。此选项需要结合-I选项一起使用。
  • -R:以递归的方式显示指定目录及其子目录中的所有内容。
  • -color:在字符模式中以颜色区分不同的文件,如果使用"--color=tty",则表示使用终端预定义的颜色方案。通常情况下,深蓝色表示目录,白色表示一般文件,绿色表示可执行的文件,黄色表示设备文件,红色表示压缩文件。

执行不带任何选项、参数的ls命令,可显示当前目录中包含的子目录、文件列表信息

# ls
splash.xpm.gz

执行"ls -ld"命令可以只显示当前目录的详细属性,而不显示目录下的内容

# ls -ld
drwxr-xr-x. 2 root root 27 5月   9 20:50 .

同时查看多个文件的信息,结合"-lh"选项可以以更易读的长格式显示

# ls -lh /etc/yum.conf /boot/vmlinuz-3.10.0-1160.el7.x86_64
-rwxr-xr-x. 1 root root 6.5M 10月 20 2020 /boot/vmlinuz-3.10.0-1160.el7.x86_64
-rw-r--r--. 1 root root  970 10月  2 2020 /etc/yum.conf

问号“?"可以匹 配文件名中的一个未知字符,而星号"*"可以匹配文件名中的任意多个字符,以长格式列出/etc/目录下以"ns"开头、".conf" 结尾的文件信息

# ls -lh /etc/ns*.conf
-rw-r--r--. 1 root root 2.0K 5月   9 20:50 /etc/nsswitch.conf

4、du命令:统计目录及文件的空间占用情况

  • -a:统计磁盘空间占用时包括所有的文件,而不仅仅只统计目录。
  • -h:以更人性化的方式(默认以KB计数,但不显示单位)显示出统计结果,使用-h选项后将显示出KB、MB等单位。
  • -s:只统计每个参数所占用空间总的(Summary)大小,而不是统计每个子目录、文件的 大小。

统计/var/log目录所占用空间的大小

# du -sh /var/log
2.9M    /var/log

分别统计/boot目录中所有文件、子目录各自占用的空间大小

# du -ah /boot/
0       /boot/efi/EFI/centos
0       /boot/efi/EFI
0       /boot/efi
4.0K    /boot/grub2/device.map
8.0K    /boot/grub2/i386-pc/gcry_rmd160.mod
12K     /boot/grub2/i386-pc/acpi.mod
4.0K    /boot/grub2/i386-pc/gcry_rsa.mod
4.0K    /boot/grub2/i386-pc/adler32.mod

5、tree树状图列出目录的内容

-C 在文件和目录清单加上色彩,便于区分各种类型

# tree -C
.
├── bin -> usr/bin
├── boot
│   ├── config-3.10.0-1160.el7.x86_64
│   ├── efi
│   │   └── EFI
│   │       └── centos
│   ├── grub
│   │   └── splash.xpm.gz
│   ├── grub2
│   │   ├── device.map
│   │   ├── fonts
│   │   │   └── unicode.pf2
│   │   ├── grub.cfg
│   │   ├── grubenv
│   │   ├── i386-pc
.............
# tree /private -L 1            # 列出目录 /private 第一级文件名
/private/
├── etc
├── tftpboot
├── tmp
└── var
# 忽略文件夹
# tree -I node_modules            # 忽略当前目录文件夹 node_modules
# tree -P node_modules            # 列出当前目录文件夹 node_modules 的目录结构
# tree -P node_modules -L 2       # 显示目录 node_modules 两层的目录树结构
# tree -L 2 > /home/www/tree.txt  # 当前目录结果存到 tree.txt 文件中
# 忽略多个文件夹
# tree -I 'node_modules|icon|font' -L 2

2、创建目录和文件

1、mkdir命令:创建新的目录

在当前目录下创建名为public的子目录

# mkdir public
# ls -d public/
public/

如果需要一次性创建嵌套的多层目录,必须结合P"选项

创建一个目录/multimedia,并在/multimedia目录下创建子目录 movie, 再在/multimedia/movie 目录下仓U建子目录 cartoon

# mkdir -p /multimedia/movie/carton

2、touch:创建空文件

touch 命令有两个功能:一是用于把已存在文件的时间标签更新为系统当前的时间(默认方式),它们的数据将原封不动地保留下来;二是用来创建空文件。

在/multimedia/movie/cartoon目录中创建两个空文件,文件名分别为huamulan.rmvb 和 nezhanaohai.mp4

# cd /multimedia/movie/carton/
# touch huamulan.rmvb nezhanaohai.mp4
# ls -lh
总用量 0
-rw-r--r--. 1 root root 0 5月   9 21:32 huamulan.rmvb
-rw-r--r--. 1 root root 0 5月   9 21:32 nezhanaohai.mp4

3、In命令:创建链接文件

ln 命令用来为文件创建连接,连接类型分为硬连接和符号连接两种,默认的连接类型是硬连接。如果要创建符号连接必须使用"-s"选项。

注意:符号链接文件不是一个独立的文件,它的许多属性依赖于源文件,所以给符号链接文件设置存取权限是没有意义的。

创建软链接 ln -s /源目录或文件 /目标目录

为文件/bin/bzip2创建一个软链接文件/bin/wx/bzip2

# mkdir /bin/wx
# ln -s /bin/bzip2 /bin/wx
# ls -lh /bin/wx/bzip2
lrwxrwxrwx. 1 root root 10 5月   9 21:34 /bin/wx/bzip2 -> /bin/bzip2

3、复制、删除、移动目录和文件

1、cp 复制文件或目录

  • -f:覆盖目标同名文件或目录时不进行提醒,而直接强制复制。
  • -i:覆盖目标同名文件或目录时提醒用户确认(交互式)。
  • -P:复制时保持源文件的权限、属主及时间标记等属性不变。
  • -r:复制目录时必须使用此选项,表示递归复制所有文件及子目录。

把/bm/touch命令程序复制到当前目录下,并命名为mytouch;另外将 /etc/yum.conf文件复制一份作为备份,添加扩展名,仍存放在/etc目录中

# cp /bin/touch ./mytouch
# cp /etc/yum.conf /etc/yum.conf.bak

目录/boot/grub、文件/etc/host.conf复制到当前目录下的public文件夹中

# cp -r /boot/grub /etc/host.conf public/
# ls public/
grub  host.conf

2、rm命令:删除文件或目录

  • -f:删除文件或目录时不进行提醒,而直接强制删除。
  • -I:删除文件或目录时提醒用户确认。
  • -r:删除目录时必须使用此选项,表示递归删除整个目录树

删除public目录中的grub目录树,且不提示用户进行确认(直接删除)

# rm -rf public/grub/
# ls public/
host.conf

以提示确认的方式删除public目录中的host.conf文件

# rm -i public/host.conf
rm:是否删除普通文件 "public/host.conf"?y

3、 mv命令:移动文件或目录

把当前目录中的mytouch程序文件改名为mkfile

# mv mytouch mkfile

把mkfile文件移动到public目录

# mv mkfile public/
# ls -l public/mkfile
-rwxr-xr-x. 1 root root 62480 5月   9 21:36 public/mkfile

4、 rmdir命令:删除空目录

# 删除子目录 test 和其父目录 zp
# rmdir -p zp/test
0

评论区