Linux 中11个比较实用的命令行,


阅读本文了解组合简单命令以创建更强大命令的可能性。

1.同时创建不同名称的文件夹

shell 的{} 运算符非常适合此操作。下面是用{} 创建三个子目录的示例:

  1. [root@localhost ~]# mkdir -p /tmp/users/{dir1,another,third} 

2. 就地编辑文件

在不使用编辑器的情况下替换一个或多个文件上的字符串,可以使用sed 来操作:

  1. [root@localhost ~]# sed -i 's/SELINUX=disabled/SELINUX=enforcing/g' /etc/selinux/config 

3. 使用web服务器快速共享文件

下面可以使用python的http.server搭建一个简易的web网站,来显示当前目录的文件,以方便下载:

  1. [root@localhost ~]# cd /root && python3 -m http.server 8080 
  2. Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ... 

4. 使用 journalctl 查询错误日志

可以使用 journalctl 以及 sort 和 uniq 的组合来查找最近的错误:

  1. [root@localhost ~]# journalctl --no-pager  --grep 'fail|error|fatal' --output json| jq '._EXE'| sort| uniq -c | sort --numeric --reverse --key 1 
  2.      45 null 
  3.      14 "/usr/bin/cat" 
  4.       6 "/usr/lib/systemd/systemd" 
  5.       6 "/usr/libexec/platform-python3.6" 
  6.       6 "/usr/bin/bash" 
  7.       5 "/usr/sbin/useradd" 
  8.       3 "/usr/sbin/rngd" 
  9.       2 "/usr/sbin/groupadd" 
  10.       1 "/usr/sbin/rsyslogd" 

5.命令行中向文件写入内容

当需要编写多行文档时,然后使用自定义的字符EOL来结束写入,这是一个很好的技巧:

  1. [root@localhost ~]# cat << EOL >> /root/documents.txt 
  2. > line 1 
  3. > line 2 
  4. > a b c d ef 
  5. > EOL 

6. 不使用 top 监控内存

使用watch命令每5秒重复一次free命令,来监测内存:

  1. [root@localhost ~]# watch -n 5 -d free -h 

7.显示磁盘分区大小

使用 lsbk 和 jq 来显示分区信息:

  1. [root@localhost ~]# lsblk --json | jq -c '.blockdevices[] | [.name,.size]' 
  2. ["sda","20G"] 
  3. ["sdb","20G"] 
  4. ["sdc","20G"] 
  5. ["sdd","20G"] 
  6. ["sr0","1024M"] 
  7. ["nvme0n1","20G"] 

8.快速显示文件的类型

下面创建一个函数,调用stat命令来显示文件名和输入的文件类型:

  1. [root@localhost ~]# function wi { test -n "$1" && stat --printf "%F\n" "$1"; } 
  2. 或者可以检查多个文件的类型: 
  3. [root@localhost ~]# function wi { test "$#" -gt 0 && stat --printf "%n: %F\n" "$@"; } 

9.显示已安装 RPM 包的大小

可以使用rpm包管理器的--queryformat选项来查看包的大小:

  1. [root@localhost ~]# rpm --queryformat='%12{SIZE} %{NAME}\n' -q adobe-mappings-cmap-20171205-3.el8.noarch 
  2.     13746679 adobe-mappings-cmap 

10.查看天气

使用此功能可以查看天气:

  1. [root@localhost ~]# weather() { curl -s --connect-timeout 3 -m 5 http://wttr.in/$1; } 

不添加参数,输出的是当前地理位置的天气,输入城市名称可以查看当地天气

11.显示访问web服务器的前 10 个 IP 地址

下面是从access.log文件中获取前十个访问web服务器的ip地址:

  1. [root@localhost httpd]# cat /var/log/nginx/access.log | cut -f 1 -d ' ' | sort | uniq -c | sort -hr | head -n 10 

相关内容