Linux基础入门

Linux命令行

控制台

Console,也就是控制台,也称为终端,提供命令行输入数据和展示命令行输出数据。

物理控制台,用于与系统交互的硬件接口。
虚拟控制台, 名称为tty1--tty6,通过ctrl + alt + F1...F6切换。tty1是图形化程序所在的终端。

ctrl + alt + F1 :进入图形化界面
ctrl + alt + F2/3 :进入虚拟控制台

shell介绍

shell是用于解析终端中输入的字符串,交由kernel执行,并将执行结果显示到终端中。Linux命令行由shell程序提供。在Linux发展过程中,产生了多种shell程序。Bash是类UNIX系统中最成功的shell,也是用户的默认shell。

shell命令提示符

作用:提示计算机正在等待用户的输入

[cyw@centos7 ~ 19:15:12]$      #代表普通用户提示符
[cyw@centos7 ~ 19:18:01]$ date #提示符最后又一个空格($与date之间有空格)
[root@centos7 cyw 19:16:37]#   #代表管理员提示符

shell解析字符串的语法

shell命令行包含三个部分,通过空格分隔:

  • 命令:第一部分一定是命令,代表要执行的程序,其后可能跟着选项或参数
  • 选项调整命令的行为或作用,通常以---开头
  • 参数:是命令的目标,命令后面可以接多个参数,也有部分命令后面可以不接参数
例: [cyw@centos7 ~ 19:18:09]$ ls -l /etc
#ls:命令;-l:选项;/etc:参数

#只使用命令:[cyw@centos7 ~ 19:28:51]$ ls
record-comand.log  公共  视频  文档  音乐  自我介绍.txt
record-time.txt    模板  图片  下载  桌面

#使用命令+选项:
[cyw@centos7 ~ 19:29:47]$ ls -a   #-a与--all都是显示所有文件,包括隐藏文件
.              .bashrc    .ICEauthority      .ssh         图片  自我介绍.txt
..             .cache     .local             .Xauthority  文档
.bash_history  .config    .mozilla           公共         下载
.bash_logout   .dbus      record-comand.log  模板         音乐
.bash_profile  .esd_auth  record-time.txt    视频         桌面

#使用参数,查看指定目标
[cyw@centos7 ~ 19:30:37]$ ls -l /etc/yum   #查看yum文件清单
总用量 4
drwxr-xr-x. 2 root root   6 10月  2 2020 fssnap.d
drwxr-xr-x. 2 root root  54 7月  14 10:43 pluginconf.d
drwxr-xr-x. 2 root root  26 7月  14 10:38 protected.d
drwxr-xr-x. 2 root root  37 10月  2 2020 vars
-rw-r--r--. 1 root root 444 10月  2 2020 version-groups.conf



命令行语法查看

在没记住语法的情况下,可通过"命令 --help"来查看具体语法:
例:
[cyw@centos7 ~ 19:36:31]$ script --help

用法:
 script [选项] [文件]

选项:
 -a, --append            追加输出
 -c, --command <命令>    运行命令而不是交互式 shell
 -e, --return            返回子进程的退出代码
 -f, --flush             每次 write(写) 后运行 flush(冲刷)
     --force             即使输出文件是链接也依然使用
 -q, --quiet             安静模式
 -t, --timing[=<文件>]   将时间数据输出到标准错误(或文件)
 -V, --version           输出版本信息并退出
 -h, --help              显示此帮助并退出

简单命令行语法实例

#显示当前时间日期
[cyw@centos7 ~ 19:37:11]$ date
2026年 07月 14日 星期二 19:38:57 CST
#显示UTC时间日期
[cyw@centos7 ~ 19:38:57]$ date -u
2026年 07月 14日 星期二 11:39:09 UTC
Try 'date --help' for more information.
[cyw@centos7 ~ 19:39:16]$ date --utc
2026年 07月 14日 星期二 11:39:28 UTC
[cyw@centos7 ~ 19:39:28]$ date --universal 
2026年 07月 14日 星期二 11:39:46 UTC
#根据给定时间字符显示日志
[cyw@centos7 ~ 19:39:54]$ date -d '-1 day' #显示一天前日期
2026年 07月 13日 星期一 19:41:46 CST
[cyw@centos7 ~ 19:41:46]$ date --date='-1 day' #显示一天前日期
2026年 07月 13日 星期一 19:42:19 CST
[cyw@centos7 ~ 19:42:19]$ date -d '100 day' #显示100天后日期
2026年 10月 22日 星期四 19:42:39 CST
#特殊案例
[cyw@centos7 ~ 19:42:50]$ date -d '-1 year +3 month +10 day'
2025年 10月 24日 星期五 19:44:18 CST
#以给定格式显示时间
[cyw@centos7 ~ 19:45:20]$ date +%Y+%m+%d
2026+07+14
#一行要执行多个命令,使用分号(;)间隔
[cyw@centos7 ~ 19:45:35]$ date;ls
2026年 07月 14日 星期二 19:46:49 CST
record-comand.log  公共  视频  文档  音乐  自我介绍.txt
record-time.txt    模板  图片  下载  桌面

bash执行命令

passwd

作用:管理用户密码
[cyw@centos7 ~ 19:48:56]$ passwd --help
用法: passwd [选项...] <帐号名称> 
#普通用户修改密码
[cyw@centos7 ~ 19:50:28]$ passwd
更改用户 cyw 的密码 。
为 cyw 更改 STRESS 密码。
(当前)UNIX 密码:
新的 密码:
无效的密码: 密码未通过字典检查 - 过于简单化/系统化
新的 密码:
无效的密码: 密码包含用户名在某些地方
新的 密码:
重新输入新的 密码:
passwd:所有的身份验证令牌已经成功更新。
#管理员用户修改密码
[root@centos7 cyw 19:52:30]# passwd cyw
更改用户 cyw 的密码 。
新的 密码:
无效的密码: 密码少于 8 个字符
重新输入新的 密码:
passwd:所有的身份验证令牌已经成功更新。
#删除用户密码
[root@centos7 cyw 19:53:01]# passwd -d cyw
清除用户的密码 cyw。
passwd: 操作成功
#锁定用户密码,用户将无法登录
[root@centos7 cyw 19:54:19]# passwd -l cyw
锁定用户 cyw 的密码 。
passwd: 操作成功
#解锁用户密码,用户可以正常登录
[root@centos7 cyw 19:54:40]# passwd -u cyw
解锁用户 cyw 的密码。
passwd: 操作成功

file

作用:判定文件类型
[cyw@centos7 ~ 20:30:51]$ file --help
Usage: file [OPTION...] [FILE...]
Determine type of FILEs.

      --help                 display this help and exit
  -v, --version              output version information and exit
  -m, --magic-file LIST      use LIST as a colon-separated list of magic
                               number files
  -z, --uncompress           try to look inside compressed files
  -b, --brief                do not prepend filenames to output lines
  -c, --checking-printout    print the parsed form of the magic file, use in
                               conjunction with -m to debug a new magic file
                               before installing it
  -e, --exclude TEST         exclude TEST from the list of test to be
                               performed for file. Valid tests are:
                               ascii, apptype, compress, elf, soft, tar, tokens, troff
  -f, --files-from FILE      read the filenames to be examined from FILE
  -F, --separator STRING     use string as separator instead of `:'
  -i, --mime                 output MIME type strings (--mime-type and
                               --mime-encoding)
      --apple                output the Apple CREATOR/TYPE
      --mime-type            output the MIME type
      --mime-encoding        output the MIME encoding
  -k, --keep-going           don't stop at the first match
  -l, --list                 list magic strength
  -L, --dereference          follow symlinks (default)
  -h, --no-dereference       don't follow symlinks
  -n, --no-buffer            do not buffer output
  -N, --no-pad               do not pad output
  -0, --print0               terminate filenames with ASCII NUL
  -p, --preserve-date        preserve access times on files
  -r, --raw                  don't translate unprintable chars to \ooo
  -s, --special-files        treat special (block/char devices) files as
                             ordinary ones
  -C, --compile              compile file specified by -m
  -d, --debug                print debugging messages

[cyw@centos7 ~ 20:33:42]$ file /etc/yum
/etc/yum: directory
# /bin/file是二进制程序
[cyw@centos7 ~ 20:32:40]$ file /bin/file
/bin/file: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, BuildID[sha1]=58f6c8b82ee70887d7136a7181ffc8fa18030cde, stripped

head

作用:显示文件头部内容
[root@centos7 cyw 19:54:50]# head --help
用法:head [选项]... [文件]...
Print the first 10 lines of each FILE to standard output.
With more than one FILE, precede each with a header giving the file name.
With no FILE, or when FILE is -, read standard input.
(将每个文件的前 10 行输出至标准输出。当指定多个文件时,每个文件内容前会打印标题行,显示文件名。若未提供文件参数,或文件名为 -,则从标准输入读取数据)

[cyw@centos7 ~ 19:59:13]$ head /etc/profile
# /etc/profile

# System wide environment and startup programs, for login setup
# Functions and aliases go in /etc/bashrc

# It's NOT a good idea to change this file unless you know what you
# are doing. It's much better to create a custom.sh shell script in
# /etc/profile.d/ to make custom changes to your environment, as this
# will prevent the need for merging in future updates.

#只看前4行
[cyw@centos7 ~ 19:59:54]$  head -n 4 /etc/profile
# /etc/profile

# System wide environment and startup programs, for login setup
# Functions and aliases go in /etc/bashrc

# 查看文件所有内容,除了最后3行
[cyw@centos7 ~ 20:00:24]$ head -n -3 /etc/profile
# /etc/profile

# System wide environment and startup programs, for login setup
# Functions and aliases go in /etc/bashrc

# It's NOT a good idea to change this file unless you know what you
# are doing. It's much better to create a custom.sh shell script in
# /etc/profile.d/ to make custom changes to your environment, as this
# will prevent the need for merging in future updates.

pathmunge () {
    case ":${PATH}:" in
        *:"$1":*)
            ;;
        *)
            if [ "$2" = "after" ] ; then
                PATH=$PATH:$1
            else
                PATH=$1:$PATH
            fi
    esac
}


if [ -x /usr/bin/id ]; then
    if [ -z "$EUID" ]; then
        # ksh workaround
        EUID=`/usr/bin/id -u`
        UID=`/usr/bin/id -ru`
    fi
    USER="`/usr/bin/id -un`"
    LOGNAME=$USER
    MAIL="/var/spool/mail/$USER"
fi

# Path manipulation
if [ "$EUID" = "0" ]; then
    pathmunge /usr/sbin
    pathmunge /usr/local/sbin
else
    pathmunge /usr/local/sbin after
    pathmunge /usr/sbin after
fi

HOSTNAME=`/usr/bin/hostname 2>/dev/null`
HISTSIZE=1000
if [ "$HISTCONTROL" = "ignorespace" ] ; then
    export HISTCONTROL=ignoreboth
else
    export HISTCONTROL=ignoredups
fi

export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE HISTCONTROL

# By default, we want umask to get set. This sets it for login shell
# Current threshold for system reserved uid/gids is 200
# You could check uidgid reservation validity in
# /usr/share/doc/setup-*/uidgid file
if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then
    umask 002
else
    umask 022
fi

for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do
    if [ -r "$i" ]; then
        if [ "${-#*i}" != "$-" ]; then 
            . "$i"
        else
            . "$i" >/dev/null
        fi
    fi
done

tail

作用:显示文件尾部内容
[cyw@centos7 ~ 20:01:58]$ tail --help
用法:tail [选项]... [文件]...
Print the last 10 lines of each FILE to standard output.
With more than one FILE, precede each with a header giving the file name.
With no FILE, or when FILE is -, read standard input.
(将每个文件的最后 10 行输出到标准输出。当传入多个文件时,每份内容前会输出标题行,展示对应文件名。如果不指定文件,或者文件参数为 -,则从标准输入读取数据)

#[cyw@centos7 ~ 20:02:47]$ tail /etc/profile
        if [ "${-#*i}" != "$-" ]; then 
            . "$i"
        else
            . "$i" >/dev/null
        fi
    fi
done

unset i
unset -f pathmunge

# 查看最后4行内容
[cyw@centos7 ~ 20:04:12]$ tail -n 4 /etc/profile
done

unset i
unset -f pathmunge

#从第四行到最后所有行内容
[cyw@centos7 ~ 20:04:24]$ tail -n +4 /etc/profile
# Functions and aliases go in /etc/bashrc

# It's NOT a good idea to change this file unless you know what you
# are doing. It's much better to create a custom.sh shell script in
# /etc/profile.d/ to make custom changes to your environment, as this
# will prevent the need for merging in future updates.

pathmunge () {
    case ":${PATH}:" in
        *:"$1":*)
            ;;
        *)
            if [ "$2" = "after" ] ; then
                PATH=$PATH:$1
            else
                PATH=$1:$PATH
            fi
    esac
}


if [ -x /usr/bin/id ]; then
    if [ -z "$EUID" ]; then
        # ksh workaround
        EUID=`/usr/bin/id -u`
        UID=`/usr/bin/id -ru`
    fi
    USER="`/usr/bin/id -un`"
    LOGNAME=$USER
    MAIL="/var/spool/mail/$USER"
fi

# Path manipulation
if [ "$EUID" = "0" ]; then
    pathmunge /usr/sbin
    pathmunge /usr/local/sbin
else
    pathmunge /usr/local/sbin after
    pathmunge /usr/sbin after
fi

HOSTNAME=`/usr/bin/hostname 2>/dev/null`
HISTSIZE=1000
if [ "$HISTCONTROL" = "ignorespace" ] ; then
    export HISTCONTROL=ignoreboth
else
    export HISTCONTROL=ignoredups
fi

export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE HISTCONTROL

# By default, we want umask to get set. This sets it for login shell
# Current threshold for system reserved uid/gids is 200
# You could check uidgid reservation validity in
# /usr/share/doc/setup-*/uidgid file
if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then
    umask 002
else
    umask 022
fi

for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do
    if [ -r "$i" ]; then
        if [ "${-#*i}" != "$-" ]; then 
            . "$i"
        else
            . "$i" >/dev/null
        fi
    fi
done

unset i
unset -f pathmunge

less

作用:交互式、翻页查看文件内容

# 使用less查看多页文档,可以翻页,搜索等
[cyw@centos7 ~ 20:05:59]$  less -N /etc/profile

# 在less查看文件过程中常见指令:
# / 搜索,n(next)搜索下一个,N搜索上一个。
# 上下方向键 逐行查看,左右键左右翻页
# pageup和pagedown 上下翻页
# q,退出文档查看

wc

作用:统计文件行数、单词数、字节数
用法:wc [选项]... [文件]...
 或:wc [选项]... --files0-from=F
Print newline, word, and byte counts for each FILE, and a total line if
more than one FILE is specified.  With no FILE, or when FILE is -,
read standard input.  A word is a non-zero-length sequence of characters
delimited by white space.
(输出每个文件的行数、单词数、字节数;如果指定多个文件,最后汇总输出总计。若未提供文件,或文件参数为 -,则从标准输入读取数据。单词定义:由空白字符分隔、长度大于 0 的字符序列)
The options below may be used to select which counts are printed, always in
the following order: newline, word, character, byte, maximum line length.
  -c, --bytes            print the byte counts
  -m, --chars            print the character counts
  -l, --lines            print the newline counts
      --files0-from=文件	从指定文件读取以NUL 终止的名称,如果该文件被
					指定为"-"则从标准输入读文件名
  -L, --max-line-length	显示最长行的长度
  -w, --words			显示单词计数
      --help		显示此帮助信息并退出
      --version		显示版本信息并退出

[cyw@centos7 ~ 20:12:05]$ wc /etc/hosts
  2  10 158 /etc/hosts

#统计文件word数量
[cyw@centos7 ~ 20:14:01]$ wc -w /etc/hosts
10 /etc/hosts
#统计文件line数量
[cyw@centos7 ~ 20:17:09]$  wc -l /etc/hosts
2 /etc/hosts
# 统计文件bytes数量
[cyw@centos7 ~ 20:14:40]$ wc -c /etc/hosts
158 /etc/hosts
# 统计多个文件数据
[cyw@centos7 ~ 20:15:11]$  wc /etc/hosts /etc/fstab
  2  10 158 /etc/hosts
 12  60 541 /etc/fstab
 14  70 699 总用量

cat

作用:一次性读取文件内容
[cyw@centos7 ~ 20:15:35]$ cat --help
用法:cat [选项]... [文件]...
将[文件]或标准输入组合输出到标准输出。

  -A, --show-all           等于-vET
  -b, --number-nonblank    对非空输出行编号
  -e                       等于-vE
  -E, --show-ends          在每行结束处显示"$"
  -n, --number             对输出的所有行编号
  -s, --squeeze-blank      不输出多行空行
  -t                       与-vT 等价
  -T, --show-tabs          将跳格字符显示为^I
  -u                       (被忽略)
  -v, --show-nonprinting   使用^ 和M- 引用,除了LFD和 TAB 之外
      --help		显示此帮助信息并退出
      --version		显示版本信息并退出


[cyw@centos7 ~ 20:16:19]$ cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
# -A选项等于-vET,用于显示行尾加个$,用^I显示制表符(tab键
[cyw@centos7 ~ 20:26:25]$ cat -A /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4$
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6$
# 一次性查看多个文件
[cyw@centos7 ~ 20:29:56]$ cat /etc/hosts /etc/fstab 
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

#
# /etc/fstab
# Created by anaconda on Tue Jul 14 10:26:40 2026
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=06075201-4e8c-4b87-872a-5a3509d9800f /boot                   xfs     defaults        0 0
/dev/mapper/centos-home /home                   xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0

tab按键

补全功能:补全命令、补全选项、补全参数
#按 tab 一次,就出结果,说明匹配结果
# 按tab 两次,才补全出结果,说明匹配结果不唯一


[cyw@centos7 ~ 20:17:49]$ pas #后面按两次tab键
passwd       paste        pasuspender  

[cyw@centos7 ~ 20:19:31]$ passwd  #pass 按一次tab键,自动补全

[cyw@centos7 ~ 20:20:11]$ passwd --delete   # passwd --del 按一次tab键,自动补全选项

[cyw@centos7 ~ 20:21:32]$ file /etc/   # file /e 按一次tab键,自动补全参数

history

作用:显示历史记录
# history命令查看帮助不能使用 history --help
[cyw@centos7 ~ 20:23:24]$ history --help
-bash: history: --: 无效选项
history: 用法:history [-c] [-d 偏移量] [n] 或 history -anrw [文件名] 或 history -ps 参数 [参数...]

[cyw@centos7 ~ 20:25:22]$ help history 
history: history [-c] [-d 偏移量] [n] 或 history -anrw [文件名] 或 history -ps 参数 [参数...]
    显示或操纵历史列表。
    
    带行号显示历史列表,将每个被修改的条目加上前缀 `*'。
    参数 N 会仅列出最后的 N 个条目。
    
    选项:
      -c	删除所有条目从而清空历史列表。
      -d 偏移量	从指定位置删除历史列表。
    
      -a	将当前绘画的历史行追加到历史文件中
      -n	从历史文件中读取所有未被读取的行
      -r	读取历史文件并将内容追加到历史列表中
    	中
      -w	将当前历史写入到历史文件中
    	并追加到历史列表中
    
      -p	对每一个 ARG 参数展开历史并显示结果
    	而不存储到历史列表中
      -s	以单条记录追加 ARG 到历史列表中
    如果给定了 FILENAME 文件名,则它将被作为历史文件。否则
    如果 $HISTFILE 变量有值的话使用之,不然使用 ~/.bash_history 文件。
    
    如果 $HISTTIMEFORMAT 变量被设定并且不为空,它的值会被用于
    strftime(3) 的格式字符串来打印与每一个显示的历史条目想关联的时
    间戳,否则不打印时间戳。
    
    退出状态:
    返回成功,除非使用了无效的选项或者发生错误。    
[cyw@centos7 ~ 20:26:08]$ history
    1  2026-07-14 19:15:08 ip -br addr
    2  2026-07-14 19:15:08 hostname
    3  2026-07-14 19:15:08 su -l root
    4  2026-07-14 19:15:08 ssh cyw@10.1.8.10
    5  2026-07-14 19:15:08 ssh cyw@10.1.8.10
    6  2026-07-14 19:15:08 pwd
    7  2026-07-14 19:15:08 init 0
    8  2026-07-14 19:15:08 su -l root
    9  2026-07-14 16:40:24 echo hello world
   10  2026-07-14 16:41:30 scriptreplay --timing record-time.txt record-comand.log
   11  2026-07-14 16:42:21 exit
...

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐