相较于Windows直观的可视化操作,Linux的许多管控任务都需要通过命令行来完成。这种操作方式,尤其在服务器编程、管理与运维场景下,显得更加简洁高效。短短一行组合命令,往往就能实现Windows中需要多个步骤才能完成的复杂功能。

1. 进程管理
w 命令可以显示当前在线用户的详细情况。
my_adm pts/0 111.111.111.111 三15 24:58 2:51 0.02s sshd: my_admin [priv]
root pts/3 111.111.111.112 13:15 3:47m 0.35s 0.35s -bash
my_adm pts/5 111.111.111.113 15:14 2.00s 0.54s 0.02s sshd: my_admin [priv]
pkill -kill -t pts/?? 可以杀掉指定终端名称的进程,例如上面的 pts/5。
2. 系统信息
arch 显示机器的处理器架构
(1) uname -m 显示机器的处理器架构
(2) uname -r 显示正在使用的内核版本
dmidecode -q 显示硬件系统部件 - (SMBIOS / DMI)
hdparm -i /dev/hda 罗列一个磁盘的架构特性
hdparm -tT /dev/sda 在磁盘上执行测试性读取操作
cat /proc/cpuinfo 显示CPU info的信息
cat /proc/interrupts 显示中断
cat /proc/meminfo 校验内存使用
cat /proc/swaps 显示哪些swap被使用
cat /proc/version 显示内核的版本
cat /proc/net/dev 显示网络适配器及统计
cat /proc/mounts 显示已加载的文件系统
lspci -tv 罗列 PCI 设备
lsusb -tv 显示 USB 设备
date 显示系统日期
ctime=`date +%Y-%m-%dT%k:%M:%S` #格式化时间,如2018-01-13T11:09:19, 注意%k 与 %H的区别,前者返回9,后者返回09.
YESTERDAY=`date +%Y-%m-%d -d "-1 days"` 获取昨日日期
cal 2007 显示2007年的日历表
date 041217002007.00 设置日期和时间 - 月日时分年.秒
clock -w 将时间修改保存到 BIOS
查询网关地址(例如将CentOS服务器网络配置从dhcp改为static时,需要获取IP和网关信息进行固化配置。假设本机IP为 10.34.0.123,可通过以下命令查询到网关为 10.34.3.254):
[root@file-server ~]# netstat -rn
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
0.0.0.0 10.34.3.254 0.0.0.0 UG 0 0 0 enp3g0
10.34.0.0 0.0.0.0 255.255.252.0 U 0 0 0 enp3g0
192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 virbr0
对于CentOS / RedHat系列,查看操作系统信息(若无 lsb_release 命令,可使用 yum install redhat-lsb 安装):
[root@server-test online]# lsb_release -a
LSB Version: :core-4.1-amd64:core-4.1-noarch
Distributor ID: CentOS
Description: CentOS Linux release 7.5.1804 (Core)
Release: 7.5.1804
Codename: Core
3. 关机 (系统的关机、重启以及登出)
shutdown -h now 关闭系统(1)
init 0 关闭系统(2)
telinit 0 关闭系统(3)
shutdown -h hours:minutes & 按预定时间关闭系统
shutdown -c 取消按预定时间关闭系统
shutdown -r now 重启(1)
reboot 重启(2)
logout 注销
4. 文件和目录
cd /home 进入 '/ home' 目录'
cd .. 返回上一级目录
cd ../.. 返回上两级目录
cd 进入个人的主目录
cd ~user1 进入个人的主目录
cd - 返回上次所在的目录
pwd 显示工作路径
ls 查看目录中的文件
ls -F 查看目录中的文件
ls -l 显示文件和目录的详细资料
ls -a 显示隐藏文件
ls *[0-9]* 显示包含数字的文件名和目录名
tree 显示文件和目录由根目录开始的树形结构(1)
lstree 显示文件和目录由根目录开始的树形结构(2)
mkdir dir1 创建一个叫做 'dir1' 的目录'
mkdir dir1 dir2 同时创建两个目录
mkdir -p /tmp/dir1/dir2 创建一个目录树
rm -f file1 删除一个叫做 'file1' 的文件'
rmdir dir1 删除一个叫做 'dir1' 的目录'
rm -rf dir1 删除一个叫做 'dir1' 的目录并同时删除其内容
rm -rf dir1 dir2 同时删除两个目录及它们的内容
mv dir1 new_dir 重命名/移动 一个目录
cp file1 file2 复制一个文件
cp dir/* . 复制一个目录下的所有文件到当前工作目录
cp -a /tmp/dir1 . 复制一个目录到当前工作目录
cp -a dir1 dir2 复制一个目录
ln -s file1 lnk1 创建一个指向文件或目录的软链接
ln file1 lnk1 创建一个指向文件或目录的物理链接
touch -t 0712250000 file1 修改一个文件或目录的时间戳 - (YYMMDDhhmm)
file file1 outputs the mime type of the file as text
iconv -l 列出已知的编码
iconv -f fromEncoding -t toEncoding inputFile > outputFile creates a new from the given input file by assuming it is encoded in fromEncoding and converting it to toEncoding.
find . -maxdepth 1 -name *.jpg -print -exec convert "{}" -resize 80x60 "thumbs/{}" \; batch resize files in the current directory and send them to a thumbnails directory (requires convert from Imagemagick)
5. 文件搜索
find / -name file1 从 '/' 开始进入根文件系统搜索文件和目录
find / -user user1 搜索属于用户 'user1' 的文件和目录
find /home/user1 -name \*.bin 在目录 '/ home/user1' 中搜索带有'.bin' 结尾的文件
find /usr/bin -type f -atime +100 搜索在过去100天内未被使用过的执行文件
find /usr/bin -type f -mtime -10 搜索在10天内被创建或者修改过的文件
find / -name \*.rpm -exec chmod 755 '{}' \; 搜索以 '.rpm' 结尾的文件并定义其权限 ^
find /tmp -name \*.hprof -exec rm -f {} \;批量删除java堆栈.hprof文件
find / -xdev -name \*.rpm 搜索以 '.rpm' 结尾的文件,忽略光驱、捷盘等可移动设备
locate \*.ps 寻找以 '.ps' 结尾的文件 - 先运行 'updatedb' 命令
whereis halt 显示一个二进制文件、源码或man的位置
which halt 显示一个二进制文件或可执行文件的完整路径
grep -rn "query_string" * Linux目录下全局查找所有文件中是否包含指定字符串(-r:递归;-n:显示行号)
6. 挂载一个文件系统
mount /dev/hda2 /mnt/hda2 挂载一个叫做hda2的盘 - 确定目录 '/ mnt/hda2' 已经存在
umount /dev/hda2 卸载一个叫做hda2的盘 - 先从挂载点 '/ mnt/hda2' 退出
fuser -km /mnt/hda2 当设备繁忙时强制卸载
umount -n /mnt/hda2 运行卸载操作而不写入 /etc/mtab 文件- 当文件为只读或当磁盘写满时非常有用
mount /dev/fd0 /mnt/floppy 挂载一个软盘
mount /dev/cdrom /mnt/cdrom 挂载一个cdrom或dvdrom
mount /dev/hdc /mnt/cdrecorder 挂载一个cdrw或dvdrom
mount /dev/hdb /mnt/cdrecorder 挂载一个cdrw或dvdrom
mount -o loop file.iso /mnt/cdrom 挂载一个文件或ISO镜像文件
mount -t vfat /dev/hda5 /mnt/hda5 挂载一个Windows FAT32文件系统
mount /dev/sda1 /mnt/usbdisk 挂载一个usb 捷盘或闪存设备
mount -t smbfs -o username=user,password=pass //WinClient/share /mnt/share 挂载一个windows网络共享
7. 磁盘空间
df -h 显示已经挂载的分区列表
ls -lSr |more 以尺寸大小排列文件和目录
du -sh dir1 估算目录 'dir1' 已经使用的磁盘空间'
du -sk * | sort -rn 以容量大小为依据依次显示文件和目录的大小
rpm -q -a --qf '%10{SIZE}t%{NAME}n' | sort -k1,1n 以大小为依据依次显示已安装的rpm包所使用的空间 (fedora, redhat类系统)
dpkg-query -W -f='${Installed-Size;10}t${Package}n' | sort -k1,1n 以大小为依据显示已安装的deb包所使用的空间 (ubuntu, debian类系统)
hdfs dfs -du /dw/default | sort -rn | head -n 10 | awk '{printf("%.2f\t\t%.2f\t\t%s\t\n",$1/1024/1024/1024,"\t"$2/1024/1024/1024,"\t"$3)}' 查询hdfs文件系统中表文件大小,按从大到小的顺序排列(取前10列),单位GB
8. 系统负载监控 -- top
top 是监控系统资源使用的强大工具,掌握它的参数能帮助我们更高效地进行系统诊断。尤其对于 Java 等后台服务的性能分析,top 的详细信息至关重要。
top -d 20 -p 1303 将进程号1303的系统负载,每隔20秒刷新一次。英文状态下,按住c键,将展示进行的详细环境信息,对于java程序调试来说,非常友好。
top -d 20 -n 3 -b > test.txt 每隔20秒,一共执行3次, 将统计结果导入到test.txt文件中。
有时候 top 命令输出显示不全,可以添加 -w 参数指定宽度。
top -b -n 1 是在批处理模式下执行一次。-b 为批处理模式,-n 为刷新的次数。
- 如果发现信息显示不全,可以使用
top -b -n 1 -w 512,-w 指定宽度为512个字符。
- 如果需要显示完整的 COMMAND 命令,使用
top -c 参数,例如 top -c -bw 500 可以按500个字符长度查看,基本能显示完整的命令。
其他重要参数说明(官方解释):
1. COMMAND-LINE Options
The command-line syntax for top consists of:
-hv|-bcHiOSs -d secs -n max -u|U user -p pid -o fld -w [cols]
The typically mandatory switch ('-') and even whitespace are completely optional.
-h | -v :Help/Version
Show library version and the usage prompt, then quit.
-b :Batch-mode operation
Starts top in Batch mode, which could be useful for sending output from top to other programs or to a file. In this mode, top will not accept input and runs until the iterations limit you've set with the `-n' command-line option or until killed.
-c :Command-line/Program-name toggle
Starts top with the last remembered `c' state reversed. Thus, if top was displaying command lines, now that field will show program names, and visa versa. See the `c' interactive command for additional information.
-d :Delay-time interval as: -d ss.t (secs.tenths)
Specifies the delay between screen updates, and overrides the corresponding value in one's personal configuration file or the startup default. Later this can be changed with the `d' or `s' interactive commands.
Fractional seconds are honored, but a negative number is not allowed. In all cases, however, such changes are prohibited if top is running in Secure mode, except for root (unless the `s' command-line option was used). For additional information on
Secure mode see topic 6a. SYSTEM Configuration File.
-H :Threads-mode operation
Instructs top to display individual threads. Without this command-line option a summation of all threads in each process is shown. Later this can be changed with the `H' interactive command.
-i :Idle-process toggle
Starts top with the last remembered `i' state reversed. When this toggle is Off, tasks that have not used any CPU since the last update will not be displayed. For additional information regarding this toggle see topic 4c. TASK AREA Commands, SIZE.
-n :Number-of-iterations limit as: -n number
Specifies the maximum number of iterations, or frames, top should produce before ending.
-o :Override-sort-field as: -o fieldname
Specifies the name of the field on which tasks will be sorted, independent of what is reflected in the configuration file. You can prepend a `+' or `-' to the field name to also override the sort direction. A leading `+' will force sorting high to
low, whereas a `-' will ensure a low to high ordering.
This option exists primarily to support automated/scripted batch mode operation.
-O :Output-field-names
This option acts as a form of help for the above -o option. It will cause top to print each of the available field names on a separate line, then quit. Such names are subject to nls translation.
-p :Monitor-PIDs mode as: -pN1 -pN2 ... or -pN1,N2,N3 ...
Monitor only processes with specified process IDs. This option can be given up to 20 times, or you can provide a comma delimited list with up to 20 pids. Co-mingling both approaches is permitted.
A pid value of zero will be treated as the process id of the top program itself once it is running.
This is a command-line option only and should you wish to return to normal operation, it is not necessary to quit and restart top -- just issue any of these interactive commands: `=', `u' or `U'.
The `p', `u' and `U' command-line options are mutually exclusive.
-s :Secure-mode operation
Starts top with secure mode forced, even for root. This mode is far better controlled through the system configuration file (see topic 6. FILES).
-S :Cumulative-time toggle
Starts top with the last remembered `S' state reversed. When Cumulative time mode is On, each process is listed with the cpu time that it and its dead children have used. See the `S' interactive command for additional information regarding this
mode.
-u | -U :User-filter-mode as: -u | -U number or name
Display only processes with a user id or user name matching that given. The `-u' option matches on effective user whereas the `-U' option matches on any user (real, effective, saved, or filesystem).
Prepending an exclamation point ('!') to the user id or name instructs top to display only processes with users not matching the one provided.
The `p', `u' and `U' command-line options are mutually exclusive.
-w :Output-width-override as: -w [ number ]
In Batch mode, when used without an argument top will format output using the COLUMNS= and LINES= environment variables, if set. Otherwise, width will be fixed at the maximum 512 columns. With an argument, output width can be decreased or increased
(up to 512) but the number of rows is considered unlimited.
In normal display mode, when used without an argument top will attempt to format output using the COLUMNS= and LINES= environment variables, if set. With an argument, output width can only be decreased, not increased. Whether using environment variables or an argument with -w, when not in Batch mode actual terminal dimensions can never be exceeded.
Note: Without the use of this command-line option, output width is always based on the terminal at which top was invoked whether or not in Batch mode.
对于希望深入学习更多系统与网络知识的读者,持续探索和总结是关键。
9. 用户和群组
groupadd group_name 创建一个新用户组
groupdel group_name 删除一个用户组
groupmod -n new_group_name old_group_name 重命名一个用户组
useradd -c "Name Surname " -g admin -d /home/user1 -s /bin/bash user1 创建一个属于 "admin" 用户组的用户
useradd user1 创建一个新用户
userdel -r user1 删除一个用户 ( '-r' 排除主目录)
usermod -c "User FTP" -g system -d /ftp/user1 -s /bin/nologin user1 修改用户属性
passwd 修改口令
passwd user1 修改一个用户的口令 (只允许root执行)
chage -E 2005-12-31 user1 设置用户口令的失效期限
pwck 检查 '/etc/passwd' 的文件格式和语法修正以及存在的用户
grpck 检查 '/etc/passwd' 的文件格式和语法修正以及存在的群组
newgrp group_name 登陆进一个新的群组以改变新创建文件的预设群组
案例 1:用户创建与组管理
1-创建用户、2-追加附加组、3-删除附加组
useradd san_zhang -m
passwd san_zhang san_zhang@163.com
从管道输出中修改密码(如果非root且可以转为root,请使用sudo)
echo san_zhang@163.com | sudo passwd --stdin san_zhang
2 将san_zhang追加到附加组hdfs中
可以添加多个附加组,多个组之间用空格隔开,如“hdfs,yarn,spark”,其默认在san_zhang中。
usermod -aG hdfs san_zhang
此时查看其所在的用户组,可以发现其所属组为san_zhang,附加组为hdfs,如下:
id san_zhang
uid=1001(san_zhang) gid=1001(san_zhang) groups=1001(san_zhang),992(hdfs)
引申:如果上一步顺序写错,误将hdfs追加到san_zhang用户组中,如使用了如下错误的命令:
usermod -aG san_zhang hdfs
则此时查看hdfs所属组,就会发现其也在san_zhang组下了。
id hdfs
uid=995(hdfs) gid=992(hdfs) groups=992(hdfs),994(hadoop),1001(san_zhang)
这时再查看san_zhang组,就会看到误加入的hdfs用户了。
groups san_zhang
san_zhang : san_zhang hdfs
3 从san_zhang组中删除误加入的hdfs用户
gpasswd -d hdfs san_zhang
执行后的日志:Removing user hdfs from group san_zhang
案例 2:统计某个分组下有哪些用户
[root@cdh01 ~]# grep hdfs /etc/group
hdfs:x:993:
[root@cdh01 ~]# awk -F : '{print $4}' /etc/passwd | grep '993'
hdfs 993
10. 文件的权限 - 使用 "+" 设置权限,使用 "-" 用于取消
ls -lh 显示权限
ls /tmp | pr -T5 -W$COLUMNS 将终端划分成5栏显示
chmod ugo+rwx directory1 设置目录的所有人(u)、群组(g)以及其他人(o)以读(r )、写(w)和执行(x)的权限
chmod go-rwx directory1 删除群组(g)与其他人(o)对目录的读写执行权限
chown user1 file1 改变一个文件的所有人属性
chown -R user1 directory1 改变一个目录的所有人属性并同时改变改目录下所有文件的属性
chgrp group1 file1 改变文件的群组
chown user1:group1 file1 改变一个文件的所有人和群组属性
find / -perm -u+s 罗列一个系统中所有使用了SUID控制的文件
chmod u+s /bin/file1 设置一个二进制文件的 SUID 位 - 运行该文件的用户也被赋予和所有者同样的权限
chmod u-s /bin/file1 禁用一个二进制文件的 SUID位
chmod g+s /home/public 设置一个目录的SGID 位 - 类似SUID ,不过这是针对目录的
chmod g-s /home/public 禁用一个目录的 SGID 位
chmod o+t /home/public 设置一个文件的 STIKY 位 - 只允许合法所有人删除文件
chmod o-t /home/public 禁用一个目录的 STIKY 位
11. 文件的特殊属性 - 使用 "+" 设置权限,使用 "-" 用于取消
chattr +a file1 只允许以追加方式读写文件
chattr +c file1 允许这个文件能被内核自动压缩/解压
chattr +d file1 在进行文件系统备份时,dump程序将忽略这个文件
chattr +i file1 设置成不可变的文件,不能被删除、修改、重命名或者链接
chattr +s file1 允许一个文件被安全地删除
chattr +S file1 一旦应用程序对这个文件执行了写操作,使系统立刻把修改的结果写到磁盘
chattr +u file1 若文件被删除,系统会允许你在以后恢复这个被删除的文件
lsattr 显示特殊的属性
12. 打包和压缩文件
bunzip2 file1.bz2 解压一个叫做 'file1.bz2'的文件
bzip2 file1 压缩一个叫做 'file1' 的文件
gunzip file1.gz 解压一个叫做 'file1.gz'的文件
gzip file1 压缩一个叫做 'file1'的文件
gzip -9 file1 最大程度压缩
rar a file1.rar test_file 创建一个叫做 'file1.rar' 的包
rar a file1.rar file1 file2 dir1 同时压缩 'file1', 'file2' 以及目录 'dir1'
unrar x file1.rar 解压rar包 #如果无unrar命令,参考:Linux CentOS 7.0 下 rar unrar的安装
tar -cvf archive.tar file1 创建一个非压缩的 tarball
tar -cvf archive.tar file1 file2 dir1 创建一个包含了 'file1', 'file2' 以及 'dir1'的档案文件
tar -tf archive.tar 显示一个包中的内容
tar -xvf archive.tar 释放一个包
tar -xvf archive.tar -C /tmp 将压缩包释放到 /tmp目录下
tar -cvfj archive.tar.bz2 dir1 创建一个bzip2格式的压缩包
tar -jxvf archive.tar.bz2 解压一个bzip2格式的压缩包
tar -cvfz archive.tar.gz dir1 创建一个gzip格式的压缩包
tar -zxvf archive.tar.gz 解压一个gzip格式的压缩包
zip file1.zip file1 创建一个zip格式的压缩包
zip -r file1.zip file1 file2 dir1 将几个文件和目录同时压缩成一个zip格式的压缩包
unzip file1.zip 解压一个zip格式压缩包
13. OS包管理器
①、RPM 包 - (Fedora, Redhat及类似系统)
rpm -ivh package.rpm 安装一个rpm包
rpm -ivh --nodeps package.rpm 安装一个rpm包而忽略依赖关系警告
rpm -U package.rpm 更新一个rpm包但不改变其配置文件
rpm -F package.rpm 更新一个确定已经安装的rpm包
rpm -e [--nodeps] package_name.rpm 删除一个rpm包[--nodeps表示忽略依赖关系]
rpm -e --nodeps `rpm -qa | grep clickhouse` 批量删除所有 ClickHouse 已安装的 rpm 包,并忽略彼此间的依赖关系
rpm -qa 显示系统中所有已经安装的rpm包
rpm -qa | grep httpd 显示所有名称中包含 "httpd" 字样的rpm包
rpm -qi package_name 获取一个已安装包的特殊信息
rpm -qg "System Environment/Daemons" 显示一个组件的rpm包
rpm -ql package_name 显示一个已经安装的rpm包提供的文件列表
rpm -qc package_name 显示一个已经安装的rpm包提供的配置文件列表
rpm -q package_name --whatrequires 显示与一个rpm包存在依赖关系的列表
rpm -q package_name --whatprovides 显示一个rpm包所占的体积
rpm -q package_name --scripts 显示在安装/删除期间所执行的脚本l
rpm -q package_name --changelog 显示一个rpm包的修改历史
rpm -qf /etc/httpd/conf/httpd.conf 确认所给的文件由哪个rpm包所提供
rpm -qp package.rpm -l 显示由一个尚未安装的rpm包提供的文件列表
rpm --import /media/cdrom/RPM-GPG-KEY 导入公钥数字证书
rpm --checksig package.rpm 确认一个rpm包的完整性
rpm -qa gpg-pubkey 确认已安装的所有rpm包的完整性
rpm -V package_name 检查文件尺寸、 许可、类型、所有者、群组、MD5检查以及最后修改时间
rpm -Va 检查系统中所有已安装的rpm包- 小心使用
rpm -Vp package.rpm 确认一个rpm包还未安装
rpm2cpio package.rpm | cpio --extract --make-directories *bin* 从一个rpm包运行可执行文件
rpm -ivh /usr/src/redhat/RPMS/`arch`/package.rpm 从一个rpm源码安装一个构建好的包
rpmbuild --rebuild package_name.src.rpm 从一个rpm源码构建一个 rpm 包
②、YUM 软件包升级器 - (Fedora, RedHat及类似系统)
yum install package_name 下载并安装一个rpm包 (如: yum -y install zip unzip)
yum localinstall package_name.rpm 将安装一个rpm包,使用你自己的软件仓库为你解决所有依赖关系
yum update package_name.rpm 更新当前系统中所有安装的rpm包
yum update package_name 更新一个rpm包
yum remove package_name 删除一个rpm包
yum list | grep tmux 列出所有可安裝的软件清单命令
yum search package_name 在rpm仓库中搜寻软件包
yum clean packages 清理rpm缓存删除下载的包
yum clean headers 删除所有头文件
yum clean all 删除所有缓存的包和头文件
③、DEB 包 (Debian, Ubuntu 以及类似系统)
dpkg -i package.deb 安装/更新一个 deb 包
dpkg -r package_name 从系统删除一个 deb 包
dpkg -l 显示系统中所有已经安装的 deb 包
dpkg -l | grep httpd 显示所有名称中包含 "httpd" 字样的deb包
dpkg -s package_name 获得已经安装在系统中一个特殊包的信息
dpkg -L package_name 显示系统中已经安装的一个deb包所提供的文件列表
dpkg --contents package.deb 显示尚未安装的一个包所提供的文件列表
dpkg -S /bin/ping 确认所给的文件由哪个deb包提供
④、APT 软件工具 (Debian, Ubuntu 以及类似系统)
apt-get install package_name 安装/更新一个 deb 包
apt-cdrom install package_name 从光盘安装/更新一个 deb 包
apt-get update 升级列表中的软件包
apt-get upgrade 升级所有已安装的软件
apt-get remove package_name 从系统删除一个deb包
apt-get check 确认依赖的软件仓库正确
apt-get clean 从下载的软件包中清理缓存
apt-cache search searched-package 返回包含所要搜索字符串的软件包名称
14. 文本查看、处理
①、查看文件内容
cat file1 从第一个字节开始正向查看文件的内容
tac file1 从最后一行开始反向查看一个文件的内容
more file1 查看一个长文件的内容
less file1 类似于 'more' 命令,但是它允许在文件中和正向操作一样的反向操作
head -2 file1 查看一个文件的前两行
tail -2 file1 查看一个文件的最后两行
tail -f /var/log/messages 实时查看被添加到一个文件中的内容
②、文本处理
cat file1 file2 ... | command <> file1_in.txt_or_file1_out.txt general syntax for text manipulation using PIPE, STDIN and STDOUT
cat file1 | command( sed, grep, awk, grep, etc...) > result.txt 合并一个文件的详细说明文本,并将简介写入一个新文件中
cat file1 | command( sed, grep, awk, grep, etc...) >> result.txt 合并一个文件的详细说明文本,并将简介写入一个已有的文件中
grep Aug /var/log/messages 在文件 '/var/log/messages'中查找关键词"Aug"
grep ^Aug /var/log/messages 在文件 '/var/log/messages'中查找以"Aug"开始的词汇
grep [0-9] /var/log/messages 选择 '/var/log/messages' 文件中所有包含数字的行
grep Aug -R /var/log/* 在目录 '/var/log' 及随后的目录中搜索字符串"Aug"
grep -E 'string_1|string_2' /var/log/test.log 在日志中同时查询包含 string_1或包含string_2的记录
# 匹配redis中, field 中包含以1到4位数字开头,以“_已下单”结尾的字符, 并将其 value 值带出来(-A1)
redis-cli -h 111.111.111.111 -p 7001 -c -a ${PASSWORD} --raw hgetall 2022-03-24_ORDER_STAT | grep -E "^[[:digit:]]{1,4}_已下单" -A1
grep -Hnr docker * 在本层或子文件夹里递归查找包含指定字符“docker”的文件,并显示文件名+行号,如果精确匹配文本,加o参数。参数含义:(H:每次匹配时将文件名打印出来;n:打印字符串所在的行号;r:递归查找;o:精确匹配到单词,多一个字符都不行)
“grep显示匹配行的上下行内容”专题:
grep -A2 2 test.txt 返回匹配行和匹配行的后两行
grep -B2 2 test.txt 返回匹配行和匹配行的前两行
grep -C2 2 text.txt 或者 grep -A2 -B2 2 test.txt 返回匹配行和匹配行的前后两行
-A -B -C 后面跟阿拉伯数字
-A 返回匹配后和它后面的n行,(After,之后)。
-B 返回匹配行和它前面的n行,(Before,之前)。
-C 返回匹配行和它前后各n行,通-A和-B联用,(Context,上下文即前后)。
sed -i 's/string1/string2/g' example.txt 将example.txt文件中的 "string1" 替换成 "string2"(如果不加-i参数,则在内存中替换; 添加-i参数,则在文件中直接替换)
sed '/^$/d' example.txt 从example.txt文件中删除所有空白行
sed '/ *#/d; /^$/d' example.txt 从example.txt文件中删除所有注释和空白行
echo 'hElloWorld' | tr '[:lower:]' '[:upper:]' 找出所有的小写字母并全部替换为大写字母
sed -e '1d' result.txt 从文件example.txt 中排除第一行
sed -n '/string1/p' 查看只包含词汇 "string1"的行
sed -e 's/ *$//' example.txt 删除每一行最后的空白字符
sed -e 's/string1//g' example.txt 从文档中只删除词汇 "string1" 并保留剩余全部
sed -n '1,5p;5q' example.txt 查看从第一行到第5行内容
sed -n '5p;5q' example.txt 查看第5行
sed -e 's/00*/0/g' example.txt 用单个零替换多个零
sed -i '3i helloword' test.txt 在test.txt文件的第三行插入‘helloword’字符串
“sed按指定字符串删除”专题:
用sed删除匹配到字符串的行。
语法:sed -i '/关键字符/d' 文件名
举例1:匹配\etc\install.sh
sed -i '/\/etc\/install.sh/d' 1.txt
-i 表示操作在源文件上生效.否则操作内存中数据,并不写入文件中. 在分号内的/d表示删除匹配的行。
举例2:删除以a开头的行
sed -i '/^a.*/d' tmp.txt
Example-1: 使用sed进行文本批量替换
#!/bin/bash
ddl_file_path=/c/Users/user/Downloads/sqoop_data/hive_2_mysql
ls $ddl_file_path | while read f;
do
echo "--------->"$ddl_file_path/$f
## Template
#sed -i 's///g' $ddl_file_path/$f
#sed -i "s///g" $ddl_file_path/$f
sed -i 's/111.111.111.111:3306/222.222.222.222:3307/g' $ddl_file_path/$f
sed -i "s/'password_1'/'password_2'/g" $ddl_file_path/$f
done
# echo -e "=========>\n\t Files contains keyword "/WARN:" in path $ddl_file_path are deleted!!!"
#!/bin/bash
set -x
# # Template
# sed -i 's///g' $ddl_file_path/$f
# sed -i "s///g" $ddl_file_path/$f
# # Func 1 - 实现在所有文件的第四行、第五行插入指定文本
ddl_file_path=/e/迅雷下载/user_data_after
ls $ddl_file_path | while read f;do
# 如果文件不是文件夹类型,才允许插入操作
if [ ! -d $f ];then
echo "--------->"$ddl_file_path/$f
sed -i '4i retries=10' $ddl_file_path/$f
sed -i '5i retry.backoff=3' $ddl_file_path/$f
fi
done
# # Func 2 - 如果文件夹不存在,则创建;反之提示文件已存在
if [ ! -d "beijing" ];then
mkdir beijing
else
echo "File already exists"
fi
文件类型的参数判别大全:
shell脚本判断文件类型 shell判断文件,目录是否存在或者具有权限
#!/bin/sh
myPath="/var/log/httpd/"
myFile="/var/log/httpd/access.log"
# 这里的-x 参数判断$myPath是否存在并且是否具有可执行权限
if [ ! -x "$myPath"]; then
mkdir "$myPath"
fi
# 这里的-d 参数判断$myPath是否存在
if [ ! -d "$myPath"]; then
mkdir "$myPath"
fi
# 这里的-f参数判断$myFile是否存在
if [ ! -f "$myFile" ]; then
touch "$myFile"
fi
# 其他参数还有-n,-n是判断一个变量是否是否有值
if [ ! -n "$myVar" ]; then
echo "$myVar is empty"
exit 0
fi
# 两个变量判断是否相等
if [ "$var1" = "$var2" ]; then
echo '$var1 eq $var2'
else
echo '$var1 not eq $var2'
fi
文件的判别逻辑大全:
-a file exists.
-b file exists and is a block special file.
-c file exists and is a character special file.
-d file exists and is a directory.
-e file exists (just the same as -a).
-f file exists and is a regular file.
-g file exists and has its setgid(2) bit set.
-G file exists and has the same group ID as this process.
-k file exists and has its sticky bit set.
-L file exists and is a symbolic link.
-n string length is not zero.
-o Named option is set on.
-O file exists and is owned by the user ID of this process.
-p file exists and is a first in, first out (FIFO) special file or named pipe.
-r file exists and is readable by the current process.
-s file exists and has a size greater than zero.
-S file exists and is a socket.
-t file descriptor number fildes is open and associated with a terminal device.
-u file exists and has its setuid(2) bit set.
-w file exists and is writable by the current process.
-x file exists and is executable by the current process.
-z string length is zero.
注意-s 和 -f 参数的区别
cat -n file1 标示文件的行数
cat example.txt | awk 'NR%2==1' 删除example.txt文件中的所有偶数行
echo a b c | awk '{print $1}' 查看一行第一栏
echo a b c | awk '{print $1,$3}' 查看一行的第一和第三栏
paste file1 file2 合并两个文件或两栏的内容
paste -d '+' file1 file2 合并两个文件或两栏的内容,中间用"+"区分
sort file1 file2 排序两个文件的内容
sort file1 file2 | uniq 取出两个文件的并集(重复的行只保留一份)
sort file1 file2 | uniq -u 删除交集,留下其他的行
sort file1 file2 | uniq -d 取出两个文件的交集(只留下同时存在于两个文件中的文件)
comm -1 file1 file2 比较两个文件的内容只删除 'file1' 所包含的内容
comm -2 file1 file2 比较两个文件的内容只删除 'file2' 所包含的内容
comm -3 file1 file2 比较两个文件的内容只删除两个文件共有的部分
综合案例:
①:本机tcp各种状态数统计
netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'
CLOSE_WAIT 2
ESTABLISHED 276
SYN_SENT 2
TIME_WAIT 63270
awk 'BEGIN { sum = 0; for (i = 0; i < 20; ++i) { sum += i; if (sum > 50) exit(10); else print "Sum =", sum } }'
②:使用cut提取文本字符串:
按“:”分割,提取/etc/passwd中第1,3,4,5列数据,按原分隔符":"进行拼接。
[hdfs@cdh01 test]$ head -n 5 /etc/passwd | cut -d : -f 1,3-5
root:0:0:root
bin:1:1:bin
daemon:2:2:daemon
adm:3:4:adm
xixi:4:7:xixi
③:使用uniq进行滤重
cut的具体用法,如下:
A).去除重复行
sort target_file | uniq
B).查找非重复行
sort target_file | uniq -u
C).查找重复行
sort target_file | uniq -d
D).统计每一个文件出现的次数
sort target_file | uniq -c
④:排序
sort是Linux下的排序工具
参数说明:
-r 降序排列
-u 去重
-n 以数字大小排序(默认是首字母排序)
-t 指定分隔符 这里我们指定'|'为分隔符
-k 指定分隔后的第几位进行排序 这里我们指定第2位
任务:report.txt文件里有以下内容:记录了一些方法的执行时间,要求按执行时间降序排列.
命令:sort -run -k 2 -t '|' report.txt
1 void com.dustpan.zeus.core.service.MergeService.startService(int)|2
2 void com.dustpan.zeus.core.service.InitShopDateService.startService(int)|1
3 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|475
4 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|96
5 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|1013
6 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|184
7 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|729
8 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|14
9 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|394
10 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|90
11 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|569
12 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|796
13 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|1648
14 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|82
15 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|1018
16 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|14
17 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|937
18 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|17
19 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|601
20 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|52
21 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|5081
22 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|388
23 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|198
24 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|1
25 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|203
26 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|1
27 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|241
28 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|13
29 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|176
30 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|12
31 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|206
32 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|3
33 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|242
34 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|19
案例一、找出本文件夹中包含my_test_calendar关键字的所有文件(含全路径+文件名),并滤重。
查询hive_sh目录下,包含搜索关键字'my_test_calendar'的文本出现的文件及关键字所在的行,将文件(文件路径+文件名) 字段提取出来,并做滤重处理。
[hdfs@nn1 hive_sh]$ find . -type f | xargs grep -rn 'my_test_calendar' | cut -d : -f 1 | uniq
案例二、查找所有出现指定文本的文件并滤重(进阶版)
脚本说明:
遍历 hive_tables.txt 文件中的所有表(如 hive_table_1),查找其在指定目录/data/program/hive_sh/下的文件中,是否使用到。如果查到重复出现该文本的文件,做滤重处理。
cat query_table_usage_in_hive.sh
#!/bin/bash
while read tbl
do
echo ------------------Handle table: $tbl--------------
find /data/program/hive_sh/ -type f | xargs grep -rn $tbl | cut -d : -f 1 | uniq > ./output/${tbl}_result.txt
done < hive_tables.txt
案例三、查找内存耗用top3的app
ps auxw | head -1;ps auxw|sort -rn -k4|head -5

以上就是一份涵盖常用场景的Linux命令参考。掌握这些命令,能极大提升在Linux环境下的工作效率。命令的学习关键在于多用、多实践,遇到具体问题时知道该用什么工具去解决。希望这份指南能成为你手边实用的速查手册。如果你对运维 & 测试领域的更多实战技巧感兴趣,可以到云栈社区与更多同行交流探讨。