linux基础命令及bash shell特性


目录

1.linux基础命令

1.1 查看内核版本和linux发行版本

  • 查看内核版本

    1. [root@xuzhichao test]# uname -r
    2. 3.10.0-1127.el7.x86_64
    3. [root@xuzhichao test]# uname -a
    4. Linux xuzhichao 3.10.0-1127.el7.x86_64 #1 SMP Tue Mar 31 23:36:51 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
  • 查看操作系统发行版本

    1. [root@xuzhichao test]# cat /etc/os-release
    2. NAME="CentOS Linux"
    3. VERSION="7 (Core)"
    4. ID="centos"
    5. ID_LIKE="rhel fedora"
    6. VERSION_ID="7"
    7. PRETTY_NAME="CentOS Linux 7 (Core)"
    8. ANSI_COLOR="0;31"
    9. CPE_NAME="cpe:/o:centos:centos:7"
    10. HOME_URL="https://www.centos.org/"
    11. BUG_REPORT_URL="https://bugs.centos.org/"
    12. CENTOS_MANTISBT_PROJECT="CentOS-7"
    13. CENTOS_MANTISBT_PROJECT_VERSION="7"
    14. REDHAT_SUPPORT_PRODUCT="centos"
    15. REDHAT_SUPPORT_PRODUCT_VERSION="7"
    16. #执行 lsb_release -a ,即可列出所有版本信息,这个命令适用于所有的linux,包括Redhat、SuSE、Debian等发行版
    17. [root@xuzhichao test]# yum install redhat-lsb-core
    18. [root@xuzhichao test]# lsb_release -a
    19. LSB Version: :core-4.1-amd64:core-4.1-noarch
    20. Distributor ID: CentOS
    21. Description: CentOS Linux release 7.8.2003 (Core)
    22. Release: 7.8.2003
    23. Codename: Core
    24. [root@xuzhichao test]# lsb_release
    25. LSB Version: :core-4.1-amd64:core-4.1-noarch
    26. #执行cat /etc/redhat-release,适用于红帽系统
    27. [root@xuzhichao test]# cat /etc/redhat-release
    28. CentOS Linux release 7.8.2003 (Core)

1.2 查看服务器硬件信息

  • 查看CPU型号

    1. #方法一:系统有两颗CPU,每个CPU一个核心
    2. [root@xuzhichao test]# lscpu
    3. Architecture: x86_64
    4. CPU op-mode(s): 32-bit, 64-bit
    5. Byte Order: Little Endian
    6. CPU(s): 2 <==共有两个CPU
    7. On-line CPU(s) list: 0,1
    8. Thread(s) per core: 1 <==每个CPU一个核心
    9. Core(s) per socket: 2
    10. Socket(s): 1
    11. NUMA node(s): 1
    12. Vendor ID: GenuineIntel
    13. CPU family: 6
    14. Model: 142
    15. Model name: Intel(R) Core(TM) i5-8265U CPU @ 1.60GHz
    16. Stepping: 11
    17. CPU MHz: 1799.999
    18. BogoMIPS: 3599.99
    19. Hypervisor vendor: VMware
    20. Virtualization type: full
    21. L1d cache: 32K
    22. L1i cache: 32K
    23. L2 cache: 256K
    24. L3 cache: 6144K
    25. NUMA node0 CPU(s): 0,1
    26. Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon nopl xtopology tsc_reliable nonstop_tsc eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid mpx rdseed adx smap clflushopt xsaveopt xsavec arat spec_ctrl intel_stibp flush_l1d arch_capabilities
    27. #方法二:
    28. [root@xuzhichao test]# cat /proc/cpuinfo
    29. processor : 0 <==CPU核心0
    30. vendor_id : GenuineIntel
    31. cpu family : 6
    32. model : 142
    33. model name : Intel(R) Core(TM) i5-8265U CPU @ 1.60GHz
    34. stepping : 11
    35. microcode : 0xde
    36. cpu MHz : 1799.999
    37. cache size : 6144 KB
    38. physical id : 0
    39. siblings : 2
    40. core id : 0
    41. cpu cores : 2
    42. apicid : 0
    43. initial apicid : 0
    44. fpu : yes
    45. fpu_exception : yes
    46. cpuid level : 22
    47. wp : yes
    48. flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon nopl xtopology tsc_reliable nonstop_tsc eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid mpx rdseed adx smap clflushopt xsaveopt xsavec arat spec_ctrl intel_stibp flush_l1d arch_capabilities
    49. bogomips : 3599.99
    50. clflush size : 64
    51. cache_alignment : 64
    52. address sizes : 43 bits physical, 48 bits virtual
    53. power management:
    54. processor : 1 <==CPU核心1
    55. vendor_id : GenuineIntel
    56. cpu family : 6
    57. model : 142
    58. model name : Intel(R) Core(TM) i5-8265U CPU @ 1.60GHz
    59. stepping : 11
    60. microcode : 0xde
    61. cpu MHz : 1799.999
    62. cache size : 6144 KB
    63. physical id : 0
    64. siblings : 2
    65. core id : 1
    66. cpu cores : 2
    67. apicid : 1
    68. initial apicid : 1
    69. fpu : yes
    70. fpu_exception : yes
    71. cpuid level : 22
    72. wp : yes
    73. flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon nopl xtopology tsc_reliable nonstop_tsc eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid mpx rdseed adx smap clflushopt xsaveopt xsavec arat spec_ctrl intel_stibp flush_l1d arch_capabilities
    74. bogomips : 3599.99
    75. clflush size : 64
    76. cache_alignment : 64
    77. address sizes : 43 bits physical, 48 bits virtual
    78. power management:
  • 查看内存大小

    1. [root@xuzhichao test]# cat /proc/meminfo
    2. MemTotal: 1863040 kB
    3. MemFree: 1031876 kB
    4. MemAvailable: 1443616 kB
    5. Buffers: 2120 kB
    6. Cached: 513628 kB
    7. SwapCached: 0 kB
    8. Active: 451992 kB
    9. Inactive: 145396 kB
    10. Active(anon): 82148 kB
    11. Inactive(anon): 9572 kB
    12. Active(file): 369844 kB
    13. Inactive(file): 135824 kB
    14. Unevictable: 0 kB
    15. Mlocked: 0 kB
    16. SwapTotal: 2097148 kB
    17. SwapFree: 2097148 kB
    18. Dirty: 0 kB
    19. Writeback: 0 kB
    20. AnonPages: 81556 kB
    21. Mapped: 31468 kB
    22. Shmem: 10080 kB
    23. Slab: 111196 kB
    24. SReclaimable: 74316 kB
    25. SUnreclaim: 36880 kB
    26. KernelStack: 4464 kB
    27. PageTables: 7020 kB
    28. NFS_Unstable: 0 kB
    29. Bounce: 0 kB
    30. WritebackTmp: 0 kB
    31. CommitLimit: 3028668 kB
    32. Committed_AS: 421208 kB
    33. VmallocTotal: 34359738367 kB
    34. VmallocUsed: 182652 kB
    35. VmallocChunk: 34359310332 kB
    36. Percpu: 33792 kB
    37. HardwareCorrupted: 0 kB
    38. AnonHugePages: 8192 kB
    39. CmaTotal: 0 kB
    40. CmaFree: 0 kB
    41. HugePages_Total: 0
    42. HugePages_Free: 0
    43. HugePages_Rsvd: 0
    44. HugePages_Surp: 0
    45. Hugepagesize: 2048 kB
    46. DirectMap4k: 92032 kB
    47. DirectMap2M: 2004992 kB
    48. DirectMap1G: 0 kB
    49. [root@xuzhichao test]# free -m
    50. total used free shared buff/cache available
    51. Mem: 1819 235 1007 9 576 1409
    52. Swap: 2047 0 2047
    53. [root@xuzhichao test]# free -th
    54. total used free shared buff/cache available
    55. Mem: 1.8G 235M 1.0G 9.8M 576M 1.4G
    56. Swap: 2.0G 0B 2.0G
    57. Total: 3.8G 235M 3.0G

1.3 关机和重启命令

  • 关机命令如下:

    • init 0
    • halt
    • poweroff
    • shutdown -h now
    • systemctl halt
  • 重启命令如下:

    • init 6
    • reboot
    • shutdown -r now
    • systemctl reboot
  • shutdown命令的语法如下:

  1. shutdown [OPTIONS...] [TIME] [WALL...]
  2. options
  3. -r --reboot 重启机器
  4. -h 关机
  5. -k 不关机,仅发送警告信息
  6. -c 取消关机操作

其中[TIME]字段为延迟关机的时间,有如下几种格式:

  1. hh:mm:24小时格式,表示在制定的时间关机或重启;
  2. +m:表示m分钟后执行关机或重启;
  3. now:表示立即关机或重启;

[WALL...]字段表示关机前发送的告警信息,会向所有的在线用户进行发送。

shutdown用法如下:

  1. #系统的23:00进行关机
  2. [root@xuzhichao ~]# shutdown -h 23:00 "The system will be shutdown at 23:00"
  3. Shutdown scheduled for Sun 2021-05-16 23:00:00 CST, use 'shutdown -c' to cancel.
  4. #取消关机
  5. [root@xuzhichao ~]# shutdown -c
  6. Broadcast message from root@xuzhichao (Sun 2021-05-16 21:26:11 CST):
  7. The system shutdown has been cancelled at Sun 2021-05-16 21:27:11 CST!
  8. #系统在10分钟后进行重启
  9. [root@xuzhichao ~]# shutdown -r +10 "The system will be reboot after 10 min"
  10. Shutdown scheduled for Sun 2021-05-16 21:38:05 CST, use 'shutdown -c' to cancel.
  11. Broadcast message from root@xuzhichao (Sun 2021-05-16 21:28:05 CST):
  12. The system will be reboot after 10 min
  13. The system is going down for reboot at Sun 2021-05-16 21:38:05 CST!

1.4 显示时间和日期命令

linux的时钟分为硬件时钟和系统时钟两种:

  1. 硬件时钟:由计算机的主板内部物理芯片计时,并由主板上的电池进行供电。
  2. 系统时钟:系统启动时,从硬件时钟读取,由linux内核通过CPU工作频率进行计时。

1.4.1 date命令

date命令语法格式如下:

  1. Usage: date [OPTION]... [+FORMAT] <==显示系统时间
  2. or: date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]] <==设定系统时间
  3. options
  4. -d, --date=STRING 显示指定字符串的时间
  5. -s, --set=STRING 设定系统时间
  6. FORMAT可用格式如下:
  7. %% a literal %
  8. %a 星期缩写 (e.g., Sun)
  9. %A 星期全写 (e.g., Sunday)
  10. %b 月份缩写 (e.g., Jan)
  11. %B 月份全写 (e.g., January)
  12. %c 时间和日期格式 (e.g., Thu Mar 3 23:05:25 2005)
  13. %d 日期,只显示数字 (e.g., 01)
  14. %D 显示日志,相当于 %m/%d/%ye.g., 05/16/21
  15. %F 完整日期,相当于%Y-%m-%de.g., 2021-05-16
  16. %H 小时,24小时制格式(00..23)
  17. %I 小时,12小时制格式 (01..12)
  18. %k 小时, 显示格式为 ( 0..23); same as %_H
  19. %l 小时, 显示格式为 ( 1..12); same as %_I
  20. %m 月,显示格式为 (01..12)
  21. %M 分钟,显示格式为 (00..59)
  22. %r 显示格式为 (e.g., 11:11:04 PM)
  23. %R 24-hour hour and minute; same as %H:%Me.g., 21:59
  24. %s 197011日到此时所经历的秒数,显示格式为1621173674
  25. %S 秒,显示格式为 (00..60)
  26. %T 显示时间,相当于%H:%M:%Se.g., 22:01:52
  27. %y 只显示年的后两位(00..99)
  28. %Y 年份(e.g., 2021

date的用法如下:

  1. #以默认格式显示当前日期
  2. [root@xuzhichao test]# date
  3. Sun May 16 22:06:31 CST 2021
  4. #以特定格式显示当前日期
  5. [root@xuzhichao test]# date +%c
  6. Sun May 16 21:52:57 2021
  7. [root@xuzhichao test]# date +%D
  8. 05/16/21
  9. [root@xuzhichao test]# date +%F
  10. 2021-05-16
  11. [root@xuzhichao test]# date +%R
  12. 21:59
  13. [root@xuzhichao test]# date +%s
  14. 1621173674
  15. [root@xuzhichao test]# date +%T
  16. 22:01:52
  17. [root@xuzhichao test]# date +"%F %T"
  18. 2021-05-16 22:05:52
  19. #以特定格式显示指定时间的日期
  20. [root@xuzhichao test]# date -d "1 day" +%F
  21. 2021-05-17
  22. [root@xuzhichao test]# date -d "-1 day" +%F
  23. 2021-05-15
  24. [root@xuzhichao test]# date +%F
  25. 2021-05-16
  26. [root@xuzhichao test]# date -d "20210101" +%F
  27. 2021-01-01
  28. [root@xuzhichao test]# date --date=20210302121212 +"%F %T"
  29. 2021030212-12-12 00:00:00
  30. [root@xuzhichao test]# date --date=20210302 +%s <==此格式多用于shell脚本中计算时间差使用
  31. 1614614400
  32. [root@xuzhichao test]# date --date='@2147483647' +"%F %T"
  33. 2038-01-19 11:14:07
  34. #设定系统时间
  35. [root@xuzhichao test]# date 030104052021.02
  36. Mon Mar 1 04:05:02 CST 2021
  37. [root@xuzhichao test]# date -s "-1 day"
  38. Sun Feb 28 04:05:20 CST 2021

1.4.2 hwclock/clock命令:操作硬件时间

hwclock用于同步硬件时间和系统时间,主要选项如下:

选项 说明
-s --hctosys 以硬件时间为准,设定系统时间
-w --systohc 以系统时间为准,设定硬件时间

hwclock命令的主要用法如下:

  1. #显示硬件时间
  2. [root@xuzhichao test]# hwclock
  3. Sun May 16 22:26:16 2021 -0.784858 seconds
  4. [root@xuzhichao test]# clock
  5. Sun May 16 22:26:18 2021 -0.362403 seconds
  6. [root@xuzhichao test]# date
  7. Sun Feb 28 04:16:40 CST 2021
  8. #以硬件时间校准系统时间
  9. [root@xuzhichao test]# hwclock -s
  10. [root@xuzhichao test]# date
  11. Sun May 16 22:26:36 CST 2021
  12. #以系统时间校准硬件时间
  13. [root@xuzhichao test]# hwclock -w
  14. [root@xuzhichao test]# hwclock
  15. Sun May 16 22:26:55 2021 -0.836115 seconds

1.4.3 cal命令:显示日历

  1. #显示当前日期的月厉
  2. [root@xuzhichao test]# cal
  3. May 2021
  4. Su Mo Tu We Th Fr Sa
  5. 1
  6. 2 3 4 5 6 7 8
  7. 9 10 11 12 13 14 15
  8. 16 17 18 19 20 21 22
  9. 23 24 25 26 27 28 29
  10. 30 31
  11. #显示指定年和月的月厉
  12. [root@xuzhichao test]# cal 9 1752
  13. September 1752
  14. Su Mo Tu We Th Fr Sa
  15. 1 2 14 15 16
  16. 17 18 19 20 21 22 23
  17. 24 25 26 27 28 29 30
  18. #显示指定年的月厉
  19. [root@xuzhichao test]# cal 2021
  20. 2021
  21. January February March
  22. Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
  23. 1 2 1 2 3 4 5 6 1 2 3 4 5 6
  24. 3 4 5 6 7 8 9 7 8 9 10 11 12 13 7 8 9 10 11 12 13
  25. 10 11 12 13 14 15 16 14 15 16 17 18 19 20 14 15 16 17 18 19 20
  26. 17 18 19 20 21 22 23 21 22 23 24 25 26 27 21 22 23 24 25 26 27
  27. 24 25 26 27 28 29 30 28 28 29 30 31
  28. 31
  29. April May June
  30. Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
  31. 1 2 3 1 1 2 3 4 5
  32. 4 5 6 7 8 9 10 2 3 4 5 6 7 8 6 7 8 9 10 11 12
  33. 11 12 13 14 15 16 17 9 10 11 12 13 14 15 13 14 15 16 17 18 19
  34. 18 19 20 21 22 23 24 16 17 18 19 20 21 22 20 21 22 23 24 25 26
  35. 25 26 27 28 29 30 23 24 25 26 27 28 29 27 28 29 30
  36. 30 31
  37. July August September
  38. Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
  39. 1 2 3 1 2 3 4 5 6 7 1 2 3 4
  40. 4 5 6 7 8 9 10 8 9 10 11 12 13 14 5 6 7 8 9 10 11
  41. 11 12 13 14 15 16 17 15 16 17 18 19 20 21 12 13 14 15 16 17 18
  42. 18 19 20 21 22 23 24 22 23 24 25 26 27 28 19 20 21 22 23 24 25
  43. 25 26 27 28 29 30 31 29 30 31 26 27 28 29 30
  44. October November December
  45. Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
  46. 1 2 1 2 3 4 5 6 1 2 3 4
  47. 3 4 5 6 7 8 9 7 8 9 10 11 12 13 5 6 7 8 9 10 11
  48. 10 11 12 13 14 15 16 14 15 16 17 18 19 20 12 13 14 15 16 17 18
  49. 17 18 19 20 21 22 23 21 22 23 24 25 26 27 19 20 21 22 23 24 25
  50. 24 25 26 27 28 29 30 28 29 30 26 27 28 29 30 31
  51. 31

1.4.4 设置时区

linux的时区文件放置在/etc/localtime文件中,通过软链接的方式指定时区。

  1. [root@xuzhichao test]# ll /etc/localtime
  2. lrwxrwxrwx. 1 root root 35 Nov 4 2020 /etc/localtime -> ../usr/share/zoneinfo/Asia/Shanghai

设置时区可以使用timedatectl命令,永久生效。

timedatectl主要命令如下:

  1. Commands:
  2. status Show current time settings
  3. set-time TIME Set system time
  4. set-timezone ZONE Set system time zone
  5. list-timezones Show known time zones
  6. set-local-rtc BOOL Control whether RTC is in local time
  7. set-ntp BOOL Control whether NTP is enabled

timedatectl命令用法如下:

  1. [root@xuzhichao test]# timedatectl status
  2. Local time: Sun 2021-05-16 22:36:32 CST
  3. Universal time: Sun 2021-05-16 14:36:32 UTC
  4. RTC time: Sun 2021-05-16 14:36:32
  5. Time zone: Asia/Shanghai (CST, +0800)
  6. NTP enabled: yes
  7. NTP synchronized: yes
  8. RTC in local TZ: no
  9. DST active: n/a
  10. [root@xuzhichao test]# timedatectl list-timezones
  11. Africa/Abidjan
  12. Africa/Accra
  13. Africa/Addis_Ababa
  14. Africa/Algiers
  15. Africa/Asmara
  16. ...(此处省略)...
  17. [root@xuzhichao test]# timedatectl set-timezone Asia/Shanghai
  18. [root@xuzhichao test]# timedatectl
  19. Local time: Sun 2021-05-16 22:37:26 CST
  20. Universal time: Sun 2021-05-16 14:37:26 UTC
  21. RTC time: Sun 2021-05-16 14:37:26
  22. Time zone: Asia/Shanghai (CST, +0800)
  23. NTP enabled: yes
  24. NTP synchronized: yes
  25. RTC in local TZ: no
  26. DST active: n/a

1.5 用户登录信息查看命令

  • who命令:显示系统当前的所有登录会话

  • w命令:显示系统当前所有登录会话及所做的操作

  • whoami命令:显示当前登录的用户

  • last命令:显示系统的历史登录用户,登录终端,ip地址,登录时间,登录时长等信息,根据/var/log/wtmp文件生成

  • lastlog命令:显示系统上所有用户的最近登录时间,根据/var/log/lastlog文件生成

    1. [root@xuzhichao test]# who
    2. root pts/0 May 16 15:56 (192.168.20.1)
    3. root pts/1 May 16 21:25 (192.168.20.1)
    4. [root@xuzhichao test]# w
    5. 09:17:57 up 17:27, 2 users, load average: 0.00, 0.01, 0.05
    6. USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
    7. root pts/0 192.168.20.1 Sun15 5.00s 0.71s 0.00s w
    8. root pts/1 192.168.20.1 21:25 11:40m 0.11s 0.11s -bash
    9. [root@xuzhichao test]# whoami
    10. root
    11. [root@xuzhichao test]# last
    12. root pts/1 192.168.20.1 Sun May 16 21:25 still logged in
    13. root pts/0 192.168.20.1 Sun May 16 15:56 still logged in
    14. reboot system boot 3.10.0-1127.el7. Sun May 16 15:51 - 09:19 (17:27)
    15. root pts/0 192.168.20.1 Sat May 15 22:51 - crash (16:59)
    16. reboot system boot 3.10.0-1127.el7. Sat May 15 22:50 - 09:19 (1+10:29)
    17. root pts/1 192.168.20.1 Thu May 13 10:30 - crash (2+12:19)
    18. root pts/0 192.168.20.1 Wed May 12 21:35 - crash (3+01:15)
    19. reboot system boot 3.10.0-1127.el7. Wed May 12 21:30 - 09:19 (4+11:48)
    20. root pts/1 192.168.20.1 Tue May 11 22:35 - down (00:53)
    21. root pts/0 192.168.20.1 Tue May 11 21:43 - down (01:44)
    22. reboot system boot 3.10.0-1127.el7. Tue May 11 21:43 - 23:28 (01:44)
    23. root pts/1 192.168.20.1 Tue May 11 10:53 - down (00:00)
    24. root pts/0 192.168.20.1 Mon May 10 17:16 - down (17:36)
    25. reboot system boot 3.10.0-1127.el7. Mon May 10 17:16 - 10:53 (17:36)
    26. root tty1 Thu May 6 18:34 - 18:34 (00:00)
    27. root pts/0 192.168.20.1 Thu May 6 12:22 - 18:34 (06:11)
    28. root pts/0 192.168.20.1 Wed May 5 21:17 - 12:22 (15:05)
    29. root pts/0 192.168.20.1 Wed May 5 21:14 - 21:16 (00:02)
    30. reboot system boot 3.10.0-1127.el7. Wed May 5 21:14 - 10:53 (5+13:39)
    31. root pts/0 192.168.20.1 Wed Apr 28 09:50 - crash (7+11:23)
    32. root pts/0 192.168.20.1 Wed Apr 28 09:48 - 09:50 (00:01)
    33. root pts/0 192.168.20.1 Wed Apr 28 09:28 - 09:48 (00:20)
    34. root tty1 Wed Apr 28 09:27 - 00:06 (14:38)
    35. reboot system boot 3.10.0-1127.el7. Wed Apr 28 09:25 - 10:53 (13+01:27)
    36. root pts/0 192.168.20.1 Tue Nov 3 17:48 - down (00:44)
    37. root pts/0 192.168.20.1 Tue Nov 3 17:47 - 17:48 (00:01)
    38. root pts/0 192.168.20.1 Tue Nov 3 17:42 - 17:47 (00:04)
    39. root pts/0 192.168.20.1 Tue Nov 3 17:37 - 17:42 (00:05)
    40. root tty1 Tue Nov 3 17:28 - 18:33 (01:04)
    41. reboot system boot 3.10.0-1127.el7. Wed Nov 4 01:27 - 18:33 (-6:-54)
    42. root tty1 Wed Nov 4 01:13 - 01:27 (00:14)
    43. root tty1 Wed Nov 4 01:12 - 01:12 (00:00)
    44. xu pts/1 :0 Wed Nov 4 01:11 - down (00:15)
    45. xu pts/0 :0 Wed Nov 4 01:11 - down (00:16)
    46. xu :0 :0 Wed Nov 4 01:11 - down (00:16)
    47. reboot system boot 3.10.0-1127.el7. Wed Nov 4 01:10 - 01:27 (00:16)
    48. reboot system boot 3.10.0-1127.el7. Wed Nov 4 01:06 - 01:27 (00:21)
    49. reboot system boot 3.10.0-1127.el7. Wed Nov 4 00:46 - 01:27 (00:40)
    50. wtmp begins Wed Nov 4 00:46:56 2020
    51. [root@xuzhichao test]# lastlog
    52. Username Port From Latest
    53. root pts/1 192.168.20.1 Sun May 16 21:25:07 +0800 2021
    54. bin **Never logged in**
    55. daemon **Never logged in**
    56. adm **Never logged in**
    57. lp **Never logged in**
    58. sync **Never logged in**
    59. shutdown **Never logged in**
    60. halt **Never logged in**
    61. mail **Never logged in**
    62. operator **Never logged in**
    63. games **Never logged in**
    64. ftp **Never logged in**
    65. nobody **Never logged in**
    66. systemd-network **Never logged in**
    67. dbus **Never logged in**
    68. polkitd **Never logged in**
    69. libstoragemgmt **Never logged in**
    70. colord **Never logged in**
    71. rpc **Never logged in**
    72. abrt **Never logged in**
    73. rtkit **Never logged in**
    74. pulse **Never logged in**
    75. chrony **Never logged in**
    76. gluster **Never logged in**
    77. ntp **Never logged in**
    78. tss **Never logged in**
    79. sssd **Never logged in**
    80. geoclue **Never logged in**
    81. mysql **Never logged in**
    82. setroubleshoot **Never logged in**
    83. gdm :0 Wed Nov 4 01:11:09 +0800 2020
    84. rpcuser **Never logged in**
    85. nfsnobody **Never logged in**
    86. sshd **Never logged in**
    87. postfix **Never logged in**
    88. tcpdump **Never logged in**
    89. xu :0 Wed Nov 4 01:11:21 +0800 2020
    90. apache **Never logged in**

1.6 echo命令

echo命令在linux中用于回显信息,也支持以特定格式显示。

echo命令的选项如下:

选项 说明
-E 不支持\解释功能(默认)
-e 支持\解释功能
-n 不自动换行

当启用-e选项时,以下字符将具有特殊意义:

字符 意义
\a 发出警告声
\b 退格键
\c 最后不加换行符
\n 换行且光标移到行首
\r 回车,光标移到行首,不换行
\t tab键
\\ 插入“\”键

echo支持输出带颜色的字体,使用如下格式:

  1. echo -e \033[字背景颜色;字体颜色m字符串\033[控制码”
  2. 字体背景颜色
  3. 40:黑 41:深红 42:绿 43:黄色 44:蓝色 45:紫色 46:深绿 47:白色
  4. 字体颜色
  5. 1:高亮 5:闪烁 30:黑 31:红 32:绿 33:黄 34:蓝色 35:紫色 36:深绿 37:白色

echo的用法如下:

  1. [root@xuzhichao test]# echo "abc"
  2. abc
  3. #显示变量
  4. [root@xuzhichao test]# echo $LANG
  5. en_US.utf8
  6. #不换行
  7. [root@xuzhichao test]# echo -n "abc"
  8. abc[root@xuzhichao test]#
  9. [root@xuzhichao test]# echo -e "abc\tcba"
  10. abc cba
  11. [root@xuzhichao test]# echo -e "\033[40;31mabc\033[m"
  12. abc

1.7 linux命令分类

linux中的命令可以分为内部命令,外部命令,别名三种。

1.7.1 内部命令

内部命令是指集成在特定shell中的命令,shell工具中默认包含了一些工具,常用的/bin/bash shell中就有很多内部命令。

shell程序是加载到内存中的,因此内部命令的执行效率很高。

  • enable命令:用于显示所有内部命令:

    1. enable -n cmd:禁用外部命令;
    2. enable cmd:启用外部命令;
  1. [root@xuzhichao test]# enable
  2. enable .
  3. enable :
  4. enable [
  5. enable alias
  6. enable bg
  7. enable bind
  8. enable break
  9. enable builtin
  10. enable caller
  11. enable cd
  12. enable command
  13. enable compgen
  14. enable complete
  15. enable compopt
  16. enable continue
  17. enable declare
  18. enable dirs
  19. enable disown
  20. enable echo
  21. enable enable
  22. enable eval
  23. enable exec
  24. enable exit
  25. enable export
  26. enable false
  27. ... (此处省略部分内容)...
  • type命令:用于判断一个命令是内部命令还是外部命令:
  1. [root@xuzhichao test]# type alias
  2. alias is a shell builtin <==内部命令为此提示
  • 内部命令的帮助信息可以使用help查看:
  1. [root@xuzhichao test]# help alias
  2. alias: alias [-p] [name[=value] ... ]
  3. Define or display aliases.
  4. Without arguments, `alias' prints the list of aliases in the reusable
  5. form `alias NAME=VALUE' on standard output.
  6. Otherwise, an alias is defined for each NAME whose VALUE is given.
  7. A trailing space in VALUE causes the next word to be checked for
  8. alias substitution when the alias is expanded.
  9. Options:
  10. -p Print all defined aliases in a reusable format
  11. Exit Status:
  12. alias returns true unless a NAME is supplied for which no alias has been
  13. defined.

1.7.2 外部命令

外部命令为独立的外部文件所提供的命令,可以使用type命令判断:

  1. [root@xuzhichao test]# type hostname
  2. hostname is /usr/bin/hostname <==外部命令可以看到命令的文件路劲
  3. [root@xuzhichao test]# hostname
  4. xuzhichao
  5. [root@xuzhichao test]# type hostname
  6. hostname is hashed (/usr/bin/hostname) <==执行过的外部文件在系统中会有缓存

外部命令实际是一个磁盘中的实际文件,当用户输入一个外部命令时,系统如果去磁盘中搜索所有的文件,那效率会相当低下。

实际上,在系统中有一个变量PATH,里面保存了外部命令存放的路径。执行外部命令时,系统会根据PATH中存放的目录顺序依次查找文件,一旦在某个目录中找到,就会停止向下查找,执行该命令。

  1. [root@xuzhichao test]# echo $PATH
  2. /usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

为了加快命令执行的速度,每次执行完外部命令时,系统会将其命令路径缓存到内存中,下次执行命令时,直接在缓存中查找路径即可,这样可以大大加快命令执行速度。

  • hash命令:用于查看外部命令缓存下来的路径

    注意:退出当前登录后hash缓存清空。

    hash选项如下:

    选项 说明
    -t NAME 打印缓存中NAME的路径
    -d NAME 删除缓存中NAME的路径
    -r 清除缓存
    -l 显示缓存,可以作为输入使用
    1. [root@xuzhichao test]# hash
    2. hits command
    3. 2 /usr/bin/hostname
    4. 1 /usr/bin/lscpu
    5. 3 /usr/bin/cal
    6. 1 /usr/bin/lastlog
    7. 6 /usr/bin/timedatectl
    8. 1 /usr/bin/last
    9. 1 /usr/bin/lastb
    10. 6 /usr/bin/rm
    11. 29 /usr/bin/date
    12. [root@xuzhichao test]# hash -l
    13. builtin hash -p /usr/bin/hostname hostname
    14. builtin hash -p /usr/bin/lscpu lscpu
    15. builtin hash -p /usr/bin/cal cal
    16. builtin hash -p /usr/bin/lastlog lastlog
    17. builtin hash -p /usr/bin/timedatectl timedatectl
    18. builtin hash -p /usr/bin/last last
    19. builtin hash -p /usr/bin/lastb lastb
    20. builtin hash -p /usr/bin/rm rm
    21. builtin hash -p /usr/bin/date date
    22. [root@xuzhichao test]# hash -d who
    23. #清空缓存
    24. [root@xuzhichao test]# hash -r
    25. [root@xuzhichao test]# hash
    26. hash: hash table empty
  • which命令:查看外部命令对应的文件路径

    1. #默认which会显示外部命令的别名和文件路径
    2. [root@xuzhichao test]# which ls
    3. alias ls='ls --color=auto'
    4. /usr/bin/ls
    5. #只显示文件路径,不显示别名
    6. [root@xuzhichao test]# which --skip-alias ls
    7. /usr/bin/ls
    8. #where命令也可以显示文件路径及其帮助文档的路径
    9. [root@xuzhichao test]# whereis ls
    10. ls: /usr/bin/ls /usr/share/man/man1/ls.1.gz /usr/share/man/man1p/ls.1p.gz

1.7.3 别名

别名:就是将一些常用的命令,起一个较短的名称,这样执行别名就相当于执行这些命令了。

  • alias命令和unalias命令用于定义和取消别名。

    1. #定义别名cdnet
    2. [root@xuzhichao test]# alias cdnet='cd /etc/sysconfig/network-scripts/'
    3. [root@xuzhichao test]# cdnet
    4. [root@xuzhichao network-scripts]# pwd
    5. /etc/sysconfig/network-scripts
    6. #查看cdnet别名
    7. [root@xuzhichao network-scripts]# alias cdnet
    8. alias cdnet='cd /etc/sysconfig/network-scripts/'
    9. #查看所有别名
    10. [root@xuzhichao network-scripts]# alias
    11. alias cdnet='cd /etc/sysconfig/network-scripts/'
    12. alias cp='cp -i'
    13. alias egrep='egrep --color=auto'
    14. alias fgrep='fgrep --color=auto'
    15. alias grep='grep --color=auto'
    16. alias l.='ls -d .* --color=auto'
    17. alias ll='ls -l --color=auto'
    18. alias ls='ls --color=auto'
    19. alias mv='mv -i'
    20. alias rm='rm -i'
    21. alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'
    22. #取消cdnet别名
    23. [root@xuzhichao network-scripts]# unalias cdnet
    24. [root@xuzhichao network-scripts]# alias cdnet
    25. -bash: alias: cdnet: not found

如果别名和某个内部或外部命令同名时,系统会优先执行别名,如果需要执行内部或外部命令可以使用以下方法:

  1. \别名;
  2. ‘别名’
  3. 命令的完整路径
  4. command 别名
  1. #默认执行别名,内容带颜色显示
  2. [root@xuzhichao ~]# ls
  3. anaconda-ks.cfg boot fstab fstab.~1~ initial-setup-ks.cfg passwd
  4. #执行外部命令ls而非别名
  5. [root@xuzhichao ~]# \ls
  6. anaconda-ks.cfg boot fstab fstab.~1~ initial-setup-ks.cfg passwd
  7. [root@xuzhichao ~]# 'ls'
  8. anaconda-ks.cfg boot fstab fstab.~1~ initial-setup-ks.cfg passwd
  9. [root@xuzhichao ~]# which ls
  10. alias ls='ls --color=auto'
  11. /usr/bin/ls
  12. [root@xuzhichao ~]# /usr/bin/ls
  13. anaconda-ks.cfg boot fstab fstab.~1~ initial-setup-ks.cfg passwd
  14. [root@xuzhichao ~]# command ls
  15. anaconda-ks.cfg boot fstab fstab.~1~ initial-setup-ks.cfg passwd
  • 设置别名永久生效

    默认情况下,使用alias命令设置的别名只对当前shell生效,永久生效需要写入配置文件中。

    • ~/.bashrc:仅针对当前用户生效;
    • /etc/bashrc:针对所有用户生效;

    编辑配置文件后别名不会立即生效,可以使用以下方法让别名生效:

    1. 重新登录shell窗口;
    2. 执行source config_path,读取配置文件;
    3. 执行. config_path,读取配置文件;
    1. #在~/.bashrc文件中增加别名
    2. [root@xuzhichao ~]# cat ~/.bashrc
    3. # .bashrc
    4. # User specific aliases and functions
    5. alias rm='rm -i'
    6. alias cp='cp -i'
    7. alias mv='mv -i'
    8. alias datetime='date +"%F %T"' <==新定义的别名
    9. # Source global definitions
    10. if [ -f /etc/bashrc ]; then
    11. . /etc/bashrc
    12. fi
    13. [root@xuzhichao ~]# datetime
    14. -bash: datetime: command not found
    15. #读取配置文件
    16. [root@xuzhichao ~]# source ~/.bashrc
    17. -bash: colorscheme: command not found
    18. [root@xuzhichao ~]# datetime
    19. 2021-05-17 12:21:04

1.7.4 linux执行命令流程

linux中执行一个命令的执行流程如下:

  1. 系统先判断是否是别名,如果是别名,则执行别名;

  2. 若不是别名,系统判断是否是内部命令,若果是,执行该内部命令;

  3. 若不是内部命令,则查询hash的缓存,若果能找到此命令对应的路径,则按照此路径执行命令,若找到的路径已经删除,则提示“no such file or directory”;

  4. 如果hash缓存中未找到此命令,则按照PATH变量中定义的路径顺序查找,一旦在某个目录中找到命令文件,则停止查找,直接执行此命令。如果PATH变量中有多个路径都有此命令文件,则只会执行排序在前的目录下的命令文件;

  5. 如果PATH变量中的所有路径都没有此命令文件,则提示“command not found”,执行失败。

    1. [root@xuzhichao ~]# who
    2. root pts/0 May 16 15:56 (192.168.20.1)
    3. root pts/1 May 16 21:25 (192.168.20.1)
    4. [root@xuzhichao ~]# hash
    5. hits command
    6. 1 /usr/bin/date
    7. 1 /usr/bin/cat
    8. 2 /usr/bin/vim
    9. 1 /usr/bin/whereis
    10. 1 /usr/bin/who
    11. 5 /usr/bin/ls
    12. #删除缓存中who命令文件,执行报错
    13. [root@xuzhichao ~]# mv /usr/bin/who /usr/bin/who.bak
    14. [root@xuzhichao ~]# who
    15. -bash: /usr/bin/who: No such file or directory
    16. [root@xuzhichao ~]# mv /usr/bin/who.bak /usr/bin/who
    17. [root@xuzhichao ~]# who
    18. root pts/0 May 16 15:56 (192.168.20.1)
    19. root pts/1 May 16 21:25 (192.168.20.1)

1.8 linux的语系

linux中已经支持很多语言和编码,通过变量和一些命令可以调整语系。

  • locale命令:显示语系。

    1. #显示本机支持的所有语系
    2. [root@xuzhichao ~]# locale -a
    3. C
    4. POSIX
    5. aa_DJ
    6. aa_DJ.iso88591
    7. aa_DJ.utf8
    8. aa_ER
    9. aa_ER.utf8
    10. aa_ER.utf8@saaho
    11. aa_ER@saaho
    12. aa_ET
    13. aa_ET.utf8
    14. af_ZA
    15. af_ZA.iso88591
    16. af_ZA.utf8
    17. am_ET
    18. #显示系统语系相关的变量
    19. [root@xuzhichao ~]# locale
    20. LANG=
    21. LC_CTYPE="POSIX"
    22. LC_NUMERIC="POSIX"
    23. LC_TIME="POSIX"
    24. LC_COLLATE="POSIX"
    25. LC_MONETARY="POSIX"
    26. LC_MESSAGES="POSIX"
    27. LC_PAPER="POSIX"
    28. LC_NAME="POSIX"
    29. LC_ADDRESS="POSIX"
    30. LC_TELEPHONE="POSIX"
    31. LC_MEASUREMENT="POSIX"
    32. LC_IDENTIFICATION="POSIX"
    33. LC_ALL=
    34. #通过设置LANG变量可以设置当前shell的语系
    35. [root@xuzhichao ~]# echo $LANG
    36. en_US.utf8
  • localectl 命令:centos7上管理语系命令,永久生效

    1. #显示当前语系
    2. [root@xuzhichao ~]# localectl
    3. System Locale: LANG=zh_CN.utf8
    4. VC Keymap: cn
    5. X11 Layout: cn
    6. #修改语系为en_US.utf8
    7. [root@xuzhichao ~]# localectl set-locale LANG=en_US.utf8
    8. [root@xuzhichao ~]# localectl
    9. System Locale: LANG=en_US.utf8
    10. VC Keymap: cn
    11. X11 Layout: cn
    12. #修改语系为zh_CN.utf8
    13. [root@xuzhichao ~]# localectl set-locale LANG=zh_CN.utf8
    14. [root@xuzhichao ~]# localectl
    15. System Locale: LANG=zh_CN.utf8
    16. VC Keymap: cn
    17. X11 Layout: cn
  • /etc/locale.conf文件是centos7上设置语系永久生效的文件

    1. [root@xuzhichao ~]# cat /etc/locale.conf
    2. LANG=en_US.utf8
  • unix和windows文件互转

    unix和windows下创建的文件在换行符上存在一些区别,Windows格式文件的换行符为\r\n ,而Unix&Linux文件的换行符为\n。

    • dos2unix命令:是将Windows格式文件转换为Unix、Linux格式

    • unix2dos命令:是将Linux&Unix格式文件转换为Windows格式。

      主要用法如下:

      1. #windows下的文件
      2. [root@xuzhichao ~]# cat windows.txt
      3. echo "ţºã¬windows"
      4. date
      5. [root@xuzhichao ~]# cat windows.txt -A
      6. echo "M-DM-cM-:M-CM-#M-,windows"^M$ <==windows下的换行符
      7. date^M$
      8. #linux下的文件
      9. [root@xuzhichao ~]# cat linux.txt -A
      10. #!/bin/bash$
      11. $
      12. echo "hello,i am linux"$ <==linux下的换行符
      13. date$
      14. #windows中的文件在linux中因为换行符不同不能执行
      15. [root@xuzhichao ~]# bash windows.txt
      16. ţºã¬windows
      17. windows.txt: line 2: $'date\r': command not found
      18. [root@xuzhichao ~]# bash linux.txt
      19. hello,i am linux
      20. Mon May 17 16:43:23 CST 2021
      21. #使用file命令查看
      22. [root@xuzhichao ~]# file windows.txt
      23. windows.txt: ISO-8859 text, with CRLF line terminators <==windows下的换行符
      24. [root@xuzhichao ~]# file linux.txt
      25. linux.txt: Bourne-Again shell script, ASCII text executable
      26. #安装dos2unix工具
      27. [root@xuzhichao ~]# yum install dos2unix -y
      28. #格式转换
      29. [root@xuzhichao ~]# dos2unix -n windows.txt windows.linux
      30. dos2unix: converting file windows.txt to file windows.linux in Unix format ...
      31. [root@xuzhichao ~]# file windows.linux
      32. windows.linux: ISO-8859 text
      33. [root@xuzhichao ~]# cat windows.linux -A
      34. echo "M-DM-cM-:M-CM-#M-,windows"$ <==转换完成后换行符发生变化
      35. date$
      36. [root@xuzhichao ~]# bash windows.linux
      37. ţºã¬windows
      38. Mon May 17 16:53:10 CST 2021

1.9 修改linux主机名

  • hostname命令:显示和修改当前的主机名:

    1. #显示当前主机名
    2. [root@xuzhichao ~]# hostname
    3. xuzhichao
    4. #修改主机名,注意:需要打开新的终端才能失效,重启设备失效
    5. [root@xuzhichao ~]# hostname abc
    6. [root@xuzhichao ~]# echo $HOSTNAME
    7. xuzhichao
    8. #放置主机名的文件
    9. [root@xuzhichao ~]# cat /etc/hostname
    10. xuzhichao
  • hostnamectl命令:显示和修改当前的主机名:

    1. #设置主机名,会连同/etc/hostname文件一起修改,重启设备主机名不会失效,需要重新打开终端生效。
    2. [root@xuzhichao ~]# hostnamectl set-hostname abc
    3. [root@xuzhichao ~]# echo $HOSTNAME
    4. xuzhichao
    5. [root@xuzhichao ~]# cat /etc/hostname
    6. abc
    7. #查看当前主机名即系统信息
    8. [root@xuzhichao ~]# hostnamectl
    9. Static hostname: abc
    10. Icon name: computer-vm
    11. Chassis: vm
    12. Machine ID: d9abb103c9b943b0bfbbb212ed3dee7f
    13. Boot ID: 18af1eea21c849cdbea8288fc3527c81
    14. Virtualization: vmware
    15. Operating System: CentOS Linux 7 (Core)
    16. CPE OS Name: cpe:/o:centos:centos:7
    17. Kernel: Linux 3.10.0-1127.el7.x86_64
    18. Architecture: x86-64
  • 有时仍需要在/etc/sysconfig/network和/etc/hosts文件中修改主机名信息。

    • /etc/hosts:域名和ip对应关系的文件

    • /etc/sysconfig/network:其中HOSTNAME=主机名字用于设置主机名

      1. [root@xuzhichao ~]# cat /etc/hosts
      2. 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 xuzhichao
      3. ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6

2.bash shell特性

shell提供了用户和内核进行交互的一种接口。shell是一种命令解释器,它把用户输入的命令送到内核中去执行。

目前linux各个发行版中主流的shell都是/bin/bash程序,系统支持的bash程序可以在/etc/shells文件中看到。

  1. [root@xuzhichao ~]# cat /etc/shells
  2. /bin/sh
  3. /bin/bash
  4. /usr/bin/sh
  5. /usr/bin/bash
  6. /bin/tcsh
  7. /bin/csh
  • /sbin/nologin是一个特殊的bash程序,该bash不能登录系统,主要用于一些系统用户使用,因为这些系统用户无需登录系统。

2.1 历史命令

bash shell会记录用户所有操作的命令到缓存区,用户注销时自动保存到~/.bash_history文件中,当用户下次登录系统时,会读取该文件中的命令到命令缓存中。

2.1.1 history命令

history命令用于显示和管理历史命令,主要选项如下:

选项 说明
-c 清空历史命令
-d offset 删除历史中第offset条命令
n 显示最近的n条命令
-a 追加本次会话新执行的命令到~/.bash_history中
-r 读取历史文件追加到历史命令列表中
-w 保存历史命令到/.bash_history文件中,会覆盖原有/.bash_history文件中的命令。慎用!
-n 读取历史文件中未读过的行到历史列表中
-p 展开历史参数成多行,但不存在历史列表中
-s 展开历史参数成一行,附加到历史列表中

history命令的用法如下:

  1. #显示历史命令
  2. [root@xuzhichao ~]# history
  3. 1 2021-05-17 18:29:36 init 3
  4. 2 2021-05-17 18:29:36 hostnamectl set-hostname Centos7-8
  5. 3 2021-05-17 18:29:36 exit
  6. 4 2021-05-17 18:29:36 ip add
  7. 5 2021-05-17 18:29:36 nmcli connection
  8. 6 2021-05-17 18:29:36 nmcli connection modify ens33 con-name ens33 ifname ens33 method none ipv4.addresses 192.168.20.27/24
  9. #显示最近3条历史命令
  10. [root@xuzhichao ~]# history 3
  11. 620 2021-05-17 18:29:43 echo $LANG
  12. 621 2021-05-17 18:30:12 history
  13. 622 2021-05-17 18:31:16 history 3
  14. #删除第623条历史命令
  15. [root@xuzhichao ~]# history 1
  16. 623 2021-05-17 18:32:08 history 1
  17. [root@xuzhichao ~]# history -d 623
  18. [root@xuzhichao ~]# history 3
  19. 622 2021-05-17 18:32:00 history -d 622
  20. 623 2021-05-17 18:32:31 history -d 623
  21. 624 2021-05-17 18:32:34 history 3
  22. #清空历史命令列表
  23. [root@xuzhichao ~]# history -c
  24. [root@xuzhichao ~]# history
  25. 247 2021-05-17 18:33:47 history
  26. [root@xuzhichao ~]# tail ~/.bash_history
  27. #1621248034
  28. hostnamectl set-hostname efg
  29. #1621248040
  30. cat /etc/hostname
  31. #1621248046
  32. hostnamectl
  33. #1621248063
  34. cat /etc/hostname
  35. #1621248755
  36. cat /etc/sysconfig/network
  37. [root@xuzhichao ~]# history
  38. 247 2021-05-17 21:41:59 history
  39. 248 2021-05-17 21:44:22 tail ~/.bash_history
  40. 249 2021-05-17 21:45:28 echo "abc"
  41. 250 2021-05-17 21:45:31 history
  42. #追加本次会话到到历史命令文件中
  43. [root@xuzhichao ~]# history -a
  44. [root@xuzhichao ~]# tail ~/.bash_history
  45. #1621258919
  46. history
  47. #1621259062
  48. tail ~/.bash_history
  49. #1621259128
  50. echo "abc"
  51. #1621259131
  52. history
  53. #1621259140
  54. history -a
  55. #清除命令列表再把命令列表覆盖写入历史命令文件中,会导致丢失历史命令。
  56. [root@xuzhichao ~]# history -c
  57. [root@xuzhichao ~]# history -w
  58. [root@xuzhichao ~]# cat ~/.bash_history
  59. #1621259799
  60. history -w
  61. #-p参数可以使得命令不记录在历史命令中,仅对部分命令有效
  62. [root@xuzhichao ~]# history -p `id`
  63. uid=0(root)
  64. gid=0(root)
  65. groups=0(root)
  66. [root@xuzhichao ~]# history
  67. 247 2021-05-17 21:56:39 history -w
  68. 248 2021-05-17 21:56:50 cat ~/.bash_history
  69. 249 2021-05-17 21:58:51 echo "aaa"
  70. 250 2021-05-17 21:58:55 history
  71. 251 2021-05-17 21:58:58 history -r
  72. 252 2021-05-17 21:56:39 history -w
  73. 253 2021-05-17 21:59:00 history
  74. 254 2021-05-17 22:00:54 history -r
  75. 255 2021-05-17 21:56:39 history -w
  76. 256 2021-05-17 22:00:57 history
  77. 257 2021-05-17 22:01:17 cat ~/.bash_history
  78. 258 2021-05-17 22:03:49 history
  79. # -s 选项可以用来在历史列表末尾添加命令,而不真正执行它们,从而在接下来的调用中可以使用它们。
  80. [root@xuzhichao ~]# history -s "rm -rf /"
  81. [root@xuzhichao ~]# history
  82. 247 2021-05-17 21:56:39 history -w
  83. 248 2021-05-17 21:56:50 cat ~/.bash_history
  84. 249 2021-05-17 21:58:51 echo "aaa"
  85. 250 2021-05-17 21:58:55 history
  86. 251 2021-05-17 21:58:58 history -r
  87. 252 2021-05-17 21:56:39 history -w
  88. 253 2021-05-17 21:59:00 history
  89. 254 2021-05-17 22:00:54 history -r
  90. 255 2021-05-17 21:56:39 history -w
  91. 256 2021-05-17 22:00:57 history
  92. 257 2021-05-17 22:01:17 cat ~/.bash_history
  93. 258 2021-05-17 22:03:49 history
  94. 259 2021-05-17 22:05:27 rm -rf /
  95. 260 2021-05-17 22:05:30 history
  • history命令中有一些变量用于控制history的相关属性

    变量及其意义如下表:

    变量名称 说明
    HISTSIZE 命令历史列表记录的最大条数,超过从时间最前的开始覆盖,默认为1000条
    HISTFILE 指定历史命令记录的文件,默认为~/.bash_history
    HISTFILESIZE 命令历史文件记录的最大条数,默认为1000条
    HISTTIMEFORMAT 指定在显示历史命令列表时同时显示时间
    HISTIGNORE 指定在历史命令中不记录的命令
    HISTCONTROL 控制历史命令的记录方式,可以设置如下值:
    1、ignoredups:默认值,忽略重复的命令,连续且相同视为重复;
    2、ignorespace:忽略所有以空格开头的命令;
    3、ignoreboth:相当于ignoredups和ignorespace的组合
    4、erasedups:删除重复命令
    1. [root@xuzhichao ~]# echo $HISTSIZE
    2. 1000
    3. [root@xuzhichao ~]# echo $HISTFILESIZE
    4. 1000
    5. [root@xuzhichao ~]# echo $HISTTIMEFORMAT
    6. %F %T
    7. [root@xuzhichao ~]# echo $HISTCONTROL
    8. ignoreboth
    9. #忽略ls开头的命令以及hostname命令
    10. [root@xuzhichao ~]# HISTIGNORE="ls*:hostname"
    11. [root@xuzhichao ~]# echo $HISTIGNORE
    12. ls*:hostname
    13. [root@xuzhichao ~]# ls /tmp
    14. dir1 file1_softlink
    15. [root@xuzhichao ~]# hostname
    16. xuzhichao
    17. #不记录上述命令的历史命令
    18. [root@xuzhichao ~]# history 3
    19. 269 2021-05-17 22:20:09 echo $HISTIGNORE
    20. 270 2021-05-17 22:20:31 history
    21. 271 2021-05-17 22:20:38 history 3

PS:如果需要永久保存上述变量,需要写入/etc/profile或~/.bash_profile文件中。

2.1.2 历史命令的快捷键

  • 重复前一个命令有4中方法:

    1. 使用向上的方向键并回车执行
    2. 使用!!并回车执行
    3. 使用 !-1 回车执行
    4. 按ctrl+p 回车执行
  • !:0:执行前一条命令(不带参数)
  • !string:重复前一个以string开头的命令
  • !n:执行history命令输出对应序号为n的命令
  • !-n:执行history命令倒数第n个命令
  • up/down:浏览从前输入的命令
  • Ctrl+r:在历史命令中搜索命令
  • Ctrl+g:退出命令历史搜索模式
  • 重新调用前一个命令的最后一个参数:
    • !$
    • Esc .
  • command !^:调用上一个命令第一个参数做为command的参数
  • command !$:调用上一个命令的最后一个参数做为command的参数
  • command !*:调用上一个命令的全部参数作为command的参数

2.2 命令行展开{}

{}:可包含一个以逗号分隔的字符串或序列,能够将其展开为多个字符串。

使用示例如下:

  1. [root@xuzhichao ~]# echo a{b,c,d}e
  2. abe ace ade
  3. [root@xuzhichao ~]# echo /tmp/{a,b,c}
  4. /tmp/a /tmp/b /tmp/c
  5. [root@xuzhichao ~]# echo {1..6}
  6. 1 2 3 4 5 6
  7. [root@xuzhichao ~]# echo {a..z}
  8. 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
  9. [root@xuzhichao ~]# echo {1..10..2}
  10. 1 3 5 7 9
  11. [root@xuzhichao ~]# echo {a..z..2}
  12. a c e g i k m o q s u w y

2.3 通配符

通配符glob,使用特定的字符,对相关的一系列文件进行匹配。

通配符的元字符如下:

元字符 说明
* 匹配任意长度字符
匹配任意单个字符
[] 中括号匹配指定集合内的任意单个字符,[xu]代表x,u两个字符中的任意一个
[0-9] 匹配任意数字
[a-z] 匹配任意单个小写字母
[[:upper:]] 匹配任意单个大写字母
[[:lower:]] 匹配任意单个小写字母
[[:digit:]] 匹配任意单个数字
[[:alnum:]] 匹配任意单个所有字母和数字
[[:alpha:]] 匹配任意单个大写和小写字母
[[:space:]] 匹配单个空白字符
[[:punctl:]] 匹配单个标点符号
[^xu] 匹配除了x,u以外的其他单个字符
[^a-z] 匹配除了小写字母以外的其他单个字符

通配符使用示例:

  1. [root@xuzhichao test]# touch file{a..d} file{A..D}
  2. [root@xuzhichao test]# ls
  3. fileA fileB fileC fileD filea fileb filec filed
  4. #显示a-z的所有文件,注意字母的排序为aAbBcCdD
  5. [root@xuzhichao test]# ls file[a-c]
  6. fileA fileB filea fileb filec
  7. [root@xuzhichao test]# ls file[[:upper:]]
  8. fileA fileB fileC fileD
  9. [root@xuzhichao test]# ls file[^aAd]
  10. fileB fileC fileD fileb filec
  11. [root@xuzhichao test]# ls /etc/rc.d/rc[0-6]*/S*
  12. /etc/rc.d/rc2.d/S10network /etc/rc.d/rc3.d/S10network /etc/rc.d/rc4.d/S10network /etc/rc.d/rc5.d/S10network
  13. #显示/etc下的非隐藏目录
  14. [root@xuzhichao test]# ls /etc/[^.]*/ -d
  15. #显示/etc下以conf结尾的文件
  16. [root@xuzhichao test]# ls /etc/*.conf

2.4 bash shell的快捷键

bash shell的常用快捷键如下:

  • Ctrl+l:清屏,相当于clear命令
  • Ctrl+c:终止命令
  • Ctrl+z:挂起当前命令,放入后台
  • Ctrl+s:阻止屏幕输出,锁定屏幕
  • Ctrl+q:允许屏幕输出
  • Ctrl+a:光标移到行首
  • Ctrl+e:光标移到行尾
  • Ctrl+u:从光标处删除到行首
  • Ctrl+k:从光标处删除到行尾
  • Alt+r:删除当前行
  • Ctrl+xx:光标在行首和光标之间移动
  • Ctrl+d:输入结束(EOF),例如邮件结束的时候

2.5 变量

2.5.1 变量的声明及引用

bash中变量需要预先定义,才能进行引用。

  • 变量的赋值格式为:

变量名=变量的值

  • 变量的引用格式为:

    在变量前加上$

    echo $NAMEecho ${NAME}

  • 删除自定义的变量:

    unset 变量名

变量的使用需要遵循如下规则:

  1. 变量两边不能直接使用空格符。

  2. 变量名称只能包含英文字母和数字,但是开头字符不能是数字。

  3. 不能使用shell中定义的命令或关键字作为变量名称。

  4. 变量内容中如有空格,使用单引号或双引号括起来。

    1. [root@xuzhichao ~]# str="a b c"
    2. [root@xuzhichao ~]# echo $str
    3. a b c
    4. [root@xuzhichao ~]# str1=a\ b\ c
    5. [root@xuzhichao ~]# echo $str1
    6. a b c
  5. 可以使用转义字符“\”将特殊符号,如[enter]、$、空格符、\、!、单引号(')等变为一般字符。

    1. [root@xuzhichao ~]# money=\$10000
    2. [root@xuzhichao ~]# echo $money
    3. $10000
    4. [root@xuzhichao ~]# money=$10000
    5. [root@xuzhichao ~]# echo $money
    6. cul0000
  6. 若变量没有赋值直接引用,变量的值为空,null。

  7. 变量引用时,若变量名与其他字符相连接,需要使用${变量名}格式

    1. [root@xuzhichao ~]# name=xuzhichao
    2. [root@xuzhichao ~]# echo $nameabc
    3. [root@xuzhichao ~]# echo ${name}abc
    4. xuzhichaoabc
    5. [root@xuzhichao ~]# echo ${name}_${str}
    6. xuzhichao_a b c
  8. 变量需要增加内容时,可以使用“\(变量名”或\){变量名}累加内容。

    1. [root@xuzhichao ~]# echo $PATH
    2. /usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
    3. [root@xuzhichao ~]# PATH=${PATH}:/usr/local/bin
    4. [root@xuzhichao ~]# echo $PATH
    5. /usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/bin
  9. 在命令中引用其他命令的结果可以使用“``”或“$()”格式。

    1. [root@xuzhichao ~]# ll `which awk`
    2. lrwxrwxrwx. 1 root root 4 Nov 4 2020 /usr/bin/awk -> gawk
    3. [root@xuzhichao ~]# version=$(uname -r)
    4. [root@xuzhichao ~]# echo $version
    5. 3.10.0-1127.el7.x86_64
    6. [root@xuzhichao ~]# touch file.log.`date +"%F %T"`
    7. [root@xuzhichao ~]# ls file.log.2021-05-18
    8. file.log.2021-05-18

2.5.2 变量类型

变量可以分为以下变量类型:

  1. 普通变量:普通变量的作用域为当前的shell进程,不包含其子进程,在shell进程结束时,普通变量会被注销。
  2. 本地变量:本地变量在函数中使用,作用域为当前函数,声明方式如下:
    • local 变量名
  3. 环境变量:环境变量用于控制shell的一些特性,作用域为当前shell及其子进程,环境变量一般使用大写字母作为变量名,声明方式如下:
    • export 变量名
    • declare -x 变量名
  4. 只读变量:根据变量是否可修改又有一种只读变量,该类型变量不能修改,声明方式如下:
    • readonly 变量名
    • declare -r 变量名

以上类型变量的使用示例如下:

  1. #普通变量声明
  2. [root@xuzhichao ~]# age=20
  3. [root@xuzhichao ~]# echo $age
  4. 20
  5. #开启一个字shell进程
  6. [root@xuzhichao ~]# bash
  7. [root@xuzhichao ~]# echo $age <==显示为空
  8. #退出到父进程
  9. [root@xuzhichao ~]# exit
  10. exit
  11. #变量仍然可以显示内容
  12. [root@xuzhichao ~]# echo $age
  13. 20
  14. #把变量声明为环境变量
  15. [root@xuzhichao ~]# export age
  16. #开启子shell进程,可以显示变量的内容
  17. [root@xuzhichao ~]# bash
  18. [root@xuzhichao ~]# echo $age
  19. 20
  20. #只读变量不能修改内容和删除变量
  21. [root@xuzhichao ~]# declare -r name=xu
  22. [root@xuzhichao ~]# name=wang
  23. -bash: name: readonly variable <==无法修改内容
  24. [root@xuzhichao ~]# unset name
  25. -bash: unset: name: cannot unset: readonly variable <==不能删除只读变量
  • 显示所有环境变量的命令如下:

    • export

    • env

    • set:显示环境变量和函数

    • declare -x

      1. [root@xuzhichao ~]# env
      2. XDG_SESSION_ID=1
      3. HOSTNAME=xuzhichao
      4. TERM=xterm
      5. SHELL=/bin/bash
      6. ...(省略部分内容)...
      7. [root@xuzhichao ~]# declare -x
      8. declare -x DISPLAY="localhost:10.0"
      9. declare -x EDITOR="vim"
      10. declare -x HISTCONTROL="ignoreboth"
      11. declare -x HISTSIZE="1000"
      12. declare -x HOME="/root"
      13. declare -x HOSTNAME="xuzhichao"
      14. ...(省略部分内容)...
      15. [root@xuzhichao ~]# export
      16. declare -x DISPLAY="localhost:10.0"
      17. declare -x EDITOR="vim"
      18. declare -x HISTCONTROL="ignoreboth"
      19. declare -x HISTSIZE="1000"
      20. declare -x HOME="/root"
      21. declare -x HOSTNAME="xuzhichao"
      22. declare -x KDEDIRS="/usr"
      23. ...(省略部分内容)...
  • declare命令:声明变量

    主要选项如下:

    选项 说明
    -a 声明数组型变量
    -i 声明变量类型为整数数字类型
    -x 声明变量类型为环境变量
    -r 声明变量类型为只读变量
    1. #默认变量类型为字符串
    2. [root@xuzhichao ~]# echo $sum
    3. 1+2+3
    4. #声明为整数类型时可以进行算数运算
    5. [root@xuzhichao ~]# declare -i sum=1+2+3
    6. [root@xuzhichao ~]# echo $sum
    7. 6

2.5.3 常用环境变量

linux中内置了一些常用的环境变量,实行了shell的特定功能。

  • UID:当前用户的UID

    1. [root@xuzhichao ~]# echo $UID
    2. 0
  • HOSTNAME:当前主机的主机名

    1. [root@xuzhichao ~]# echo $HOSTNAME
    2. xuzhichao
  • HOME:当前用户的家目录

    1. [root@xuzhichao ~]# echo $HOME
    2. /root
  • SHELL:当前使用的shell类型

    1. [root@xuzhichao ~]# echo $SHELL
    2. /bin/bash
  • MAIL:当前用户的邮件文件存放目录

    1. [root@xuzhichao ~]# echo $MAIL
    2. /var/spool/mail/root
  • PATH:执行外部命令查找的路径,路径之间使用:分割

  • LANG:系统使用的语系和字符编码集

  • $、BASHPID :都表示当前shell的PID

    1. [root@xuzhichao ~]# echo $BASHPID
    2. 3738
    3. [root@xuzhichao ~]# echo $$
    4. 3738
  • PS1:shell的命令提示符

    1. [root@xuzhichao ~]# echo $PS1
    2. \[\e[1;36m\][\u@\h \W]\$ \[\e[0m\] <==带颜色显示
    3. \u:当前用户账号信息
    4. \h:主机第一个小数点之前的命令
    5. \w:当前完整工作目录
    6. \$:提示符,root提示#,其他用户提示$
    7. \#:执行的第n条命令
  • PS2:命令过长或一条命令分两行写第二行的提示符

    1. [root@xuzhichao ~]# echo $PS2
    2. >
  • RANDOM:随机数,随机数范围为0~32768

    1. [root@xuzhichao ~]# echo $RANDOM
    2. 7283
    3. [root@xuzhichao ~]# declare -i num=$RANDOM*10/32768; echo $num <==取0-10之间的随机数
    4. 6
  • ?:上一个执行的命令的回传码,0代表上一个命令执行成功,1-255代表上一个命令出现了各种错误。

    1. [root@xuzhichao ~]# ls anaconda-ks.cfg
    2. anaconda-ks.cfg
    3. [root@xuzhichao ~]# echo $?
    4. 0
    5. [root@xuzhichao ~]# ls abc
    6. ls: cannot access abc: No such file or directory
    7. [root@xuzhichao ~]# echo $?
    8. 2
    9. [root@xuzhichao ~]# echo $?
    10. 0

2.5.4 单引号、双引号、反向单引号

在使用变量时,单引号、双引号、反向单引号的区别如下:

  • 单引号:强引用,变量内容使用单引号时,对其中的命令和变量都无法识别,只能识别为字符串本身。 最傻
  • 双引号:弱引用,变量内容使用双引号时,对其中的命令无法识别,但是变量可以识别,显示变量的内容。 中间傻
  • 反向单引号:变量内容使用反向单引号时,对其中的命令和变量都可以识别,执行命令,显示变量内容。 最聪明

使用示例如下:

  1. [root@xuzhichao ~]# echo "echo username is $USER"
  2. echo username is root
  3. [root@xuzhichao ~]# echo 'echo username is $USER'
  4. echo username is $USER
  5. [root@xuzhichao ~]# echo `echo username is $USER`
  6. username is root

2.6 bash shell命令的执行逻辑

2.6.1 分号连接多个命令

把多个命令合并在一起执行,缺点是无论前一个命令是否执行成功都会执行下一个命令。若命令之间存在逻辑性,则会存在问题。

使用格式如下:

  • command1;command2;command3

使用示例:

  1. [root@xuzhichao ~]# ls a ; cd /data ; pwd
  2. ls: cannot access a: No such file or directory
  3. /data
  4. [root@xuzhichao data]# sync ; sync ; shutdown -h 0

2.6.2 小括号()包含多个命令

小括号()包含多个命令,可以一次执行多个命令,提高执行效率。

使用格式如下:

  • (command1;command2;command3)

注意:小括号会开启一个字shell进程,所有在()中的变量不会影响到当前shell的变量。

  1. [root@xuzhichao /]# ls /data/ ; pwd ; (cd /data;pwd);pwd
  2. python python-v1.1 python-v1.2 test <==ls /data/的结果
  3. / <==第二个pwd的执行结果
  4. /data <==()中的pwd执行结果
  5. / <==最后一个pwd的执行结果,在()中的执行的cd /data命令不会影响当前shell的环境
  6. [root@xuzhichao ~]# name=123;(name=abc; echo $name);echo $name
  7. abc
  8. 123 <==()中变量的赋值不会影响当前shell的变量

2.6.3 大括号{}包含多个命令

大括号{}包含多个命令,可以一次执行多个命令,提高执行效率。

使用格式如下:

  • { command1;command2;command3; }

    注意:{ }和命令之间至少要有一个空格,且最后一个命令需要以分号;结束

注意:大括号{}中不会开启子shell,{}中的命令是在当前shell下执行的,会对当前shell的变量产生影响

  1. [root@xuzhichao ~]# name=123;{ name=abc; echo $name; };echo $name
  2. abc
  3. abc

2.6.4 && 和||的用法

多个命令之间如果存在逻辑判断关系,例如前一个命令执行成功则执行下一条命令,此时就需要&&和||的帮助了。

  • cmd1 && cmd2:若cmd1执行完毕且正确执行(\(?=0)则开始执行cmd2,若cmd1执行完毕但是执行错误(\)?!=0),则cmd2不执行。
  • cmd1 || cmd2:若cmd1执行完毕且正确执行(\(?=0)则不开始执行cmd2,若cmd1执行完毕但是执行错误(\)?!=0),则开始执行cmd2。

&&和||的用法示例如下:

  1. #/data/test目录如果存在则在该目录下创建file1文件
  2. [root@xuzhichao ~]# ls /data/test && touch /data/test/file1
  3. ls: cannot access /data/test: No such file or directory
  4. [root@xuzhichao ~]# ll /data/test/file1
  5. ls: cannot access /data/test/file1: No such file or directory <==因为/data/test不存在,file1没有创建
  6. [root@xuzhichao ~]# mkdir /data/test
  7. [root@xuzhichao ~]# ls /data/test && touch /data/test/file1
  8. [root@xuzhichao ~]# ls /data/test/file1
  9. /data/test/file1 <==因为/data/test已经存在,故file1创建成功
  10. #/data/test如果不存在就创建该目录
  11. [root@xuzhichao ~]# rm -rf /data/test/
  12. [root@xuzhichao ~]# ls /data/test/ || mkdir /data/test/
  13. ls: cannot access /data/test/: No such file or directory
  14. [root@xuzhichao ~]# ll /data/test/ -d
  15. drwxr-xr-x 2 root root 6 May 18 23:52 /data/test/ <==因为/data/test不存在,故/data/test创建成功
  16. #无论/date/test/目录是否存在,都需要在/data/test下创建/data/test/file1文件
  17. #当ls /data/test/命令运行失败时,执行mkdir /data/test/和touch /data/test/file1,当ls /data/test/命令运行成功时,只执行ch /data/test/file1命令
  18. [root@xuzhichao ~]# rm -rf /data/test/
  19. [root@xuzhichao ~]# ls /data/test/ || mkdir /data/test/ && touch /data/test/file1
  20. ls: cannot access /data/test/: No such file or directory
  21. [root@xuzhichao ~]# ls /data/test/file1
  22. /data/test/file1
  23. #判断/data/test/目录是否存在,存在则显示exist,不存在则显示not exist
  24. [root@xuzhichao ~]# ls /data/test/ &> /dev/null && echo "exist" || echo "not exist"
  25. exist
  26. [root@xuzhichao ~]# rm -rf /data/test/
  27. [root@xuzhichao ~]# ls /data/test/ &> /dev/null && echo "exist" || echo "not exist"
  28. not exist

注意:以上两个例子中&&和||混合使用时&&和||放置的位置,位置不同实现的功能也不通。

2.7 I/O重定向

  • I/0数据流:

    I/0数据流分为标准输入STDIN,标准输出STDOUT和标准错误输出STFERR三种,标准输入一般从键盘实现,标准输出一般从屏幕实现,三个都可以修改。

  • 文件描述符fd:

    当程序打开一个文件时,linux会自动分配一个软链接,指向正在打开的文件,这就是文件描述符。

    文件描述符一般是一个正整数,是内核为了高效管理已打开的文件的索引,所有执行I/0操作的系统调用都需要使用fd。

  • 当一个程序启动时,会自动打开STDIN,STDOUT,STDERR这三个I/0设备文件,这三个I/0设备文件对应的文件描述符分别是0,1,2.这个程序打开的其他文件的描述符从3开始计数。

    1. #查看当前shell打开的fd
    2. [root@xuzhichao ~]# ll /proc/$BASHPID/fd
    3. total 0
    4. lrwx------ 1 root root 64 May 19 09:42 0 -> /dev/pts/1 <==标准输入,从pts/1输入
    5. lrwx------ 1 root root 64 May 19 09:42 1 -> /dev/pts/1
    6. lrwx------ 1 root root 64 May 19 09:42 2 -> /dev/pts/1
    7. lrwx------ 1 root root 64 May 19 10:14 255 -> /dev/pts/1
    8. #查看当前PID为1的进程打开的文件描述符
    9. [root@xuzhichao ~]# ll /proc/1/fd
    10. total 0
    11. lrwx------ 1 root root 64 May 18 17:01 0 -> /dev/null <==标准输入,指向/dev/null即为不输入
    12. lrwx------ 1 root root 64 May 18 17:01 1 -> /dev/null <==标准输出
    13. lr-x------ 1 root root 64 May 19 10:09 10 -> anon_inode:inotify
    14. lr-x------ 1 root root 64 May 19 10:09 11 -> /proc/swaps <==打开的文件的fd
    15. lrwx------ 1 root root 64 May 19 10:09 12 -> socket:[10974]
    16. lr-x------ 1 root root 64 May 19 10:09 14 -> anon_inode:inotify
    17. lrwx------ 1 root root 64 May 19 10:09 19 -> socket:[10979]
    18. lrwx------ 1 root root 64 May 18 17:01 2 -> /dev/null <==错误输出
    19. lrwx------ 1 root root 64 May 19 10:09 20 -> /run/dmeventd-server
  • I/O重定向实现方法:

    I/O类型 操作符 意义
    标准覆盖输出重定向 1> (1可以省略) 将程序输出的正确结果输出到指定的文件中,会覆盖文件原有的内容
    标准追加输出重定向 1>> (1可以省略) 将程序输出的正确结果输出到指定的文件中,会追加到文件原有的内容后面
    错误覆盖输出重定向 2> 将程序输出的错误结果输出到指定的文件中,会覆盖文件原有的内容
    错误追加输出重定向 2>> 将程序输出的错误结果输出到指定的文件中,会追加到文件原有的内容后面
    输入重定向 0< (0可以省略) 从指定的文件中向程序输入内容
    多行输入重定向 << 一次向程序输入多行内容
  • set -C命令:禁止将内容覆盖已有文件,可以追加。

    1. #设置文件内容禁止覆盖
    2. [root@xuzhichao ~]# set -C
    3. [root@xuzhichao ~]# ls > file1
    4. [root@xuzhichao ~]# ls > file1
    5. -bash: file1: cannot overwrite existing file <==文件不能覆盖
    6. #使用 >| file 方式可以强行覆盖文件
    7. [root@xuzhichao ~]# ls >| file1
    8. #取消文件内容禁止覆盖
    9. [root@xuzhichao ~]# set +C

2.7.1 输出重定向

输出重定向分为以下三种类型:

  • 标准输出重定向

    1. #hostname命令重定向到/dev/pts/1终端上输出,本终端不在输出到屏幕中。
    2. [root@xuzhichao ~]# hostname > /dev/pts/1
    3. #把ls命令存放到stdout.txt文件中,>>可实现追加
    4. #当stdout.txt不存在时,会自动创建,存在时,使用>会覆盖其内容
    5. [root@xuzhichao ~]# ls > stdout.txt
    6. [root@xuzhichao ~]# cat stdout.txt
    7. anaconda-ks.cfg
    8. [root@xuzhichao ~]# ls > stdout.txt
    9. [root@xuzhichao ~]# cat stdout.txt
    10. anaconda-ks.cfg
    11. #追加内容而不覆盖
    12. [root@xuzhichao ~]# ls >> stdout.tx
    13. [root@xuzhichao ~]# cat stdout.txt
    14. anaconda-ks.cfg
    15. anaconda-ks.cfg
  • 错误输出重定向

    1. #文件不存在,有错误输出
    2. [root@xuzhichao ~]# ls err
    3. ls: cannot access err: No such file or directory
    4. #把错误输出指向文件stderr.txt
    5. [root@xuzhichao ~]# ls err 2> stderr.txt
    6. [root@xuzhichao ~]# ls err 2> stderr.txt
    7. [root@xuzhichao ~]# cat stderr.txt
    8. ls: cannot access err: No such file or directory
    9. #把错误输出追加到文件stderr.txt
    10. [root@xuzhichao ~]# ls err 2>> stderr.txt
    11. [root@xuzhichao ~]# cat stderr.txt
    12. ls: cannot access err: No such file or directory
    13. ls: cannot access err: No such file or directory
  • 标准输出和错误输出结合使用

    标准输出和错误输出可以同时使用,分别输出到不同的地方,也可以同时输出到同一个地方,使用如下方式:

    • &> file

    • > file 2>&1

      第一种命令实现的逻辑示例图如下:

  1. 第二种命令实现的逻辑示例图如下:

  1. ```shell
  2. #示例一:把标准输出重定向到stdout.txt,把错误输出重定向到stderr.txt
  3. [root@xuzhichao ~]# ls /data/ err > stdout.txt 2> stderr.txt
  4. #示例二:把标准输出和错误输出合并到一个文件stdall.txt
  5. [root@xuzhichao ~]# ls /data/ err &> stdall.txt
  6. [root@xuzhichao ~]# ls /data/ err > stdall.txt 2>&1
  7. #示例三:把标准输出和错误输出合并到一个文件stdall.txt,使用追加的方式
  8. [root@xuzhichao ~]# ls /data/ err >> stdall.txt 2>&1
  9. [root@xuzhichao ~]# ls /data/ err &>> stdall.txt
  10. #示例四:使用/dev/null可以把一些不需要的输出屏蔽掉,/dev/null称为垃圾桶。
  11. #使用id命令判断xu用户是否存在
  12. [root@xuzhichao ~]# id xu &> /dev/null
  13. [root@xuzhichao ~]# echo $?
  14. 0 <==结果为0代表用户xu存在
  15. #示例五:把多条命令的正确执行结果合并到一个文件
  16. [root@xuzhichao ~]# (id xu ; date) > all.log
  17. [root@xuzhichao ~]# cat all.log
  18. uid=1000(xu) gid=1000(xu) groups=1000(xu)
  19. Wed May 19 11:45:11 CST 2021
  20. #示例六:通过覆盖软链接可以把真实文件覆盖
  21. [root@xuzhichao ~]# cat all.log
  22. uid=1000(xu) gid=1000(xu) groups=1000(xu)
  23. Wed May 19 11:45:11 CST 2021
  24. [root@xuzhichao ~]# ln -s all.log all.link
  25. [root@xuzhichao ~]# ll all.*
  26. lrwxrwxrwx 1 root root 7 May 19 11:47 all.link -> all.log
  27. -rw-r--r-- 1 root root 71 May 19 11:45 all.log
  28. [root@xuzhichao ~]# > all.link
  29. [root@xuzhichao ~]# cat all.log <==内容被覆盖
  30. [root@xuzhichao ~]#
  31. ```

2.7.2 输入重定向

很多命令的默认是从键盘获取数据,可以使用文件来代替键盘获取输入。

  1. #示例一:使用文件中的y作为rm命令的输入
  2. [root@xuzhichao ~]# rm f1
  3. rm: remove regular empty file 'f1'? y
  4. [root@xuzhichao ~]# echo "y" > y.txt
  5. [root@xuzhichao ~]# rm f2 < y.txt
  6. rm: remove regular empty file 'f2'?
  7. #示例二:利用标准输入,备份文件
  8. [root@xuzhichao ~]# echo "welcome" > /etc/motd
  9. [root@xuzhichao ~]# cat > motd.bak < /etc/motd
  10. [root@xuzhichao ~]# cat motd.bak
  11. welcome
  12. #示例三:使用文件作为cat的输入
  13. [root@xuzhichao ~]# cat < /etc/issue
  14. \S
  15. Kernel \r on an \m

2.7.3 多行输入重定向

当我们需要一次性输入多行数据,批量提交时,可以使用多行重定向实现。

多行重定向格式为:

  1. command << [-] 结束符
  2. line1
  3. line2
  4. ...
  5. 结束符
  6. 说明:
  7. 1.结束符可以是任意字符,但需要保持一致,一般使用EOF
  8. 2.结束符必须为独立的一行,前后不能有其他字符;
  9. 3.“-”一般用于在脚本中实现对齐效果;

使用示例如下:

  1. [root@xuzhichao ~]# cat > file1 <<EOF
  2. > abc
  3. > 123
  4. > qwe
  5. > EOF
  6. [root@xuzhichao ~]# cat file1
  7. abc
  8. 123
  9. qwe

2.8 管道

利用管道符“|”可以把两个无关的程序结合起来实现复杂功能。管道可以把前一个程序输出的结果作为后一个程序的输入进行处理。

管道使用格式如下:

  • command1 | command2 | command3

注意:管道只能用于传递前一个命令的标准输出,不能传递错误输出。

如果需要让command2接收command1的错误输出,可以使用如下格式:

  • command1 2>&1 | command2
  • command1 |& command2

管道的使用示例如下:

  1. [root@xuzhichao ~]# echo "1+1" | bc
  2. 2
  3. [root@xuzhichao ~]# echo {1..100} | tr ' ' '+' | bc
  4. 5050
  5. [root@xuzhichao ~]# ls
  6. 22:18:01 all.link all.log anaconda-ks.cfg boot file.log.2021-05-18 file1 fstab fstab.~1~ initial-setup-ks.cfg
  7. [root@xuzhichao ~]# ls | tr 'a-z' 'A-Z'
  8. 22:18:01
  9. ALL.LINK
  10. ALL.LOG
  11. ANACONDA-KS.CFG
  12. BOOT
  13. FILE.LOG.2021-05-18
  14. FILE1
  15. FSTAB
  16. FSTAB.~1~
  17. INITIAL-SETUP-KS.CFG
  18. #处理前一个命令的错误输出
  19. [root@xuzhichao ~]# ls err | tr 'a-z' 'A-Z'
  20. ls: cannot access err: No such file or directory
  21. [root@xuzhichao ~]# ls err |& tr 'a-z' 'A-Z'
  22. LS: CANNOT ACCESS ERR: NO SUCH FILE OR DIRECTORY

2.8.1 tee命令

tee命令可以接收标准输入,实现同时将数据分送到文件和屏幕。实现的逻辑如下:

tee命令的语法格式:

  1. tee [OPTION]... [FILE]...
  2. -a, --append 追加到文件,而非覆盖

tee用法如下:

  1. [root@xuzhichao ~]# hostname | tee -a tee.log | tr 'a-z' 'A-Z'
  2. XUZHICHAO
  3. [root@xuzhichao ~]# cat tee.log
  4. xuzhichao

2.8.2 减号“-”的用法

在管道中,经常会使用前一个命令的输出作为后一个命令的输入,当某些命令需要使用到文件名来处理时,stdin和stdout就可以使用减号“-”来代替文件。

示例:

  1. #将/home目录的内容备份到当前目录下。
  2. [root@xuzhichao ~]# tar -cvf - /home/ | tar -xvf -

这个例子意思是将/home目录下的文件打包,打包的数据不是记录到文件,而是传送到stdout;经过管道后将-传送给后一个命令tar -xvf - ,这样后一个命令的“-”则是取前一个命令的stdout,这样我们就不需要临时文件了。

linux基础命令及bash shell特性的更多相关文章

  1. Linux基础命令---enable开启shell命令

    enable enable指令用来关闭或者激活shell内部命令.此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora. 1.语法       enable [-a]   ...

  2. 【Python之路】第一篇--Linux基础命令

    pwd 命令 查看”当前工作目录“的完整路径 pwd -P # 显示出实际路径,而非使用连接(link)路径:pwd显示的是连接路径 .   表示当前目录 ..  表示上级目录 /  表示根目录 ls ...

  3. linux基础命令一

    linux基础命令一 1.date命令 date命令介绍:显示或者设置系统日期 date命令的语法: 显示日期:date  [options...]  [+FORMAT] FORMAT:为显示日期的格 ...

  4. 常用的linux基础命令

    常用的linux基础命令 1.ls 显示目录属性 -l:(也可以简写成ll),列表显示权限等属性 -a:显示所有文件包括隐藏文件等 -d:只列出目录本身 2.chgrp 改变档案所属群组 eg:chg ...

  5. Linux基础命令-查看基本硬件信息

    Linux基础命令-查看基本硬件信息 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.查看CPU信息 [root@node101.yinzhengjie.org.cn ~]# l ...

  6. Linux基础命令小结(超全!!)

    Linux目录结构 1.bin 存放经常使用的指令比如ll,cp 2.sbin 系统管理员使用的系统管理指令 3.home 存放普通用户的住目录 4.root 系统管理员的用户主目录 5.boot 存 ...

  7. Linux基础命令整合

    linux基础命令整理 1.系统相关命令 shutdown -h now 关闭系统(1) init 0 关闭系统(2) telinit 0 关闭系统(3) shutdown -h hours:minu ...

  8. Linux——基础命令用法(上)

    一.Linux基础命令 1.Linux命令行的格式 命令行的格式为:用户名+主机名+当前工作目录 输入内容的命令格式为:命令 [-短选项/--长选项] [参数] [root@localhost ~]# ...

  9. 第四节,Linux基础命令

    第四节,Linux基础命令 命令是系统操作员对系统传入的指令,传入指令后回车,系统接收到指令做出相应的行为 1.查看用户位于系统什么位置 [pmd]检查操作用户位于系统的什么位置 命令         ...

  10. Linux编程 3 (初识bash shell与man查看手册)

    一.初识bash shell 1.1 启动 shell   GNU bash shell 能提供对Linux系统的交互式访问.通常是在用户登录终端时启动,登录时系统启动shell依赖于用户账户的配置. ...

随机推荐

  1. java实战:多属性排序

    多属性排序的核心点就是对Arrays.sort()和Collections.sort()方法的Comparator进行重写 Arrays.sort()的三种用法 1.1.Arrays.sort(int ...

  2. AndroidStudio--app是如何运行的

    #实用快捷键# Ctrl+alt+F 快速自动把类方法内部的变量声明为类属性变量,以方便全局使用! Ctrl+O  快速显示所有类方法以及field属性结构 今天发现了一个非常好的博主----litt ...

  3. 【WCH以太网接口系列芯片】CH9121\9120、CH395\392以太网系列芯片的硬件电路注意事项

    本篇基于沁恒微电子官方的以太网接口芯片的DEMO参考原理图进行分析,对一些注意事项进行标注,如果硬件设计上出现问题可以对照参考. CH912x系列: 1.CH9121:建议设计中可以将31脚RUN脚预 ...

  4. #凸包,闵可夫斯基和#CF87E Mogohu-Rea Idol

    题目 按逆时针顺序给出三个凸包点集 \(\mathbb{A,B,C}\),每次查询给出点 \(D\), 问是否存在点 \(A\in\mathbb{A},B\in\mathbb{B},C\in\math ...

  5. #差分约束,SPFA#洛谷 1993 小 K 的农场

    题目 分析 对于描述1,也就是\((a,b,-c)\),\(b\)比\(a\)至多多\(-c\) 对于描述2,也就是\((b,a,c)\),\(a\)比\(b\)至多多\(c\) 对于描述3,也就是\ ...

  6. C#使用PaddleOCR进行图片文字识别✨

    PaddlePaddle介绍 PaddlePaddle(飞桨)是百度开发的深度学习平台,旨在为开发者提供全面.灵活的工具集,用于构建.训练和部署各种深度学习模型.它具有开放源代码.高度灵活性.可扩展性 ...

  7. openGauss Sqlines 使用指导

    openGauss Sqlines 使用指导 Sqlines 简介 Sqlines 是一款开源软件,支持多种数据库之间的 SQL 语句语法的的转换,openGauss 将此工具修改适配,新增了 ope ...

  8. CS101

    Turing machine:图灵机 理论上可以计算任何东西 CPU(Center Process Unit):中央处理器 是现代电脑的"大脑",其中包含数十亿细小开关的硅片,即晶 ...

  9. keystore 生成密钥

    前言 在安卓中,我们需要生存keystore来处理我们的证书: 我们很幸运在keystore中,在java中的bin下,已经有了keytool工具了,感谢java社区工作者. 正文 在命令窗口中使用k ...

  10. Gowin 1nr-9k mipi测试

    本次实验是利用gowin 1nr-9k的开发板测试MIPI屏. 测试的屏是2.0寸的,接口如下: 接上IO就是RST和MIPI的时钟和数据接口,另外就是电源和地. Gowin的案例中,首先是软件要升级 ...