Linux常用命令大全(非常全面)

目录

一、进程管理 

二、系统信息 

三、关机 (系统的关机、重启以及登出 ) 

四、文件和目录 

五、文件搜索 

六、挂载一个文件系统 

七、磁盘空间 

八、系统负载 -- top 

九、用户和群组 

十、文件的权限 - 使用 "+" 设置权限,使用 "-" 用于取消 

十一、文件的特殊属性 - 使用 "+" 设置权限,使用 "-" 用于取消 

十二、打包和压缩文件 

十三、OS包管理器

①、RPM 包 - (Fedora, Redhat及类似系统) 

②、YUM 软件包升级器 - (Fedora, RedHat及类似系统) 

③、DEB 包 (Debian, Ubuntu 以及类似系统) 

④、APT 软件工具 (Debian, Ubuntu 以及类似系统) 

十四、文本查看、处理

①、查看文件内容 

②、文本处理 

十五、vim专题 

①、大小写转换

②、字符串处理专题

③、vi中文本操作

④、vim基础操作

⑤、shell脚本中的注释(单行注释/多行注释)

十五、字符设置和文件格式转换 

十六、文件系统分析 

十七、初始化一个文件系统 

十八、SWAP文件系统 

十九、备份 

二十、光盘操作 

二一、网络 - (以太网和WIFI无线) 

二二、JPS工具

二三、crontab调度器

①、语法

二四、Shell编程相关

①、内置变量

②、数据结构

1、数组

for i in in {1..10}; do rm -f hadoop-cmf-hive-HIVEMETASTORE-nn1.testhdp.com.log.out.$i;done

2、字典dict 或 Map

3、管道输出中执行下一条指令

4、循环、迭代逻辑控制

5、break 与 contine区别

6、大文件拆分处理

7、awk

8、实现脚本中切换用户并执行该用户相关的命令操作

③、echo在shell中控制颜色&闪烁显示

1、在shell中显示色彩

二十五、程序开机自启动服务配置 

二十六、持续监控Linux命令的执行情况



Linux和windows相比,很多管控都需要用命令来操作。windows以直观的可视化的方式操作,特别适合在桌面端PC上操作执行相应的软件。

而Linux命令行方式的操作,特别是在服务器端编程、管理、运维方面,更加简单、短小、精悍。短短一行组合命令,即可完成在windows需要各种加工、整合的复杂高效的功能操作。 

一、进程管理 


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

传送门:Linux中Kill进程的N种方法

二、系统信息 


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,则通过如下命令查询到网关为第一个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


三、关机 (系统的关机、重启以及登出 ) 


shutdown -h now 关闭系统(1) 
init 0 关闭系统(2) 
telinit 0 关闭系统(3) 
shutdown -h hours:minutes & 按预定时间关闭系统 
shutdown -c 取消按预定时间关闭系统 
shutdown -r now 重启(1) 
reboot 重启(2) 
logout 注销 


四、文件和目录 


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) 
 


五、文件搜索 


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:显示行号)


六、挂载一个文件系统 


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网络共享 

 


七、磁盘空间 


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

八、系统负载 -- 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为刷新的次数
发现信息显示不全,最后man top,加一个参数w后,完全显示

top -b -n 1 -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 vari‐
            ables 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.


九、用户和群组 

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-删除附加组
# 1
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
usermod -aG hdfs san_zhang (将san_zhang追加到附加组hdfs中(可以添加多个附加组,多个组之间用空格隔开,如"hdfs,yarn,spark"),其默认在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
gpasswd -d hdfs san_zhang (从san_zhang组中删除误加入的hdfs用户)
执行后的日志:Removing user hdfs from group san_zhang
#-----------------------------------------------------

案例 2:

统计某个分组下有哪些用户

[root@cdh01 ~]# grep hdfs /etc/group
hdfs:x:993:

[root@cdh01 ~]# awk -F : '{print $1,$4}' /etc/passwd | grep '993'
hdfs 993



 


十、文件的权限 - 使用 "+" 设置权限,使用 "-" 用于取消 


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 位 

 


十一、文件的特殊属性 - 使用 "+" 设置权限,使用 "-" 用于取消 

chattr +a file1 只允许以追加方式读写文件 
chattr +c file1 允许这个文件能被内核自动压缩/解压 
chattr +d file1 在进行文件系统备份时,dump程序将忽略这个文件 
chattr +i file1 设置成不可变的文件,不能被删除、修改、重命名或者链接 
chattr +s file1 允许一个文件被安全地删除 
chattr +S file1 一旦应用程序对这个文件执行了写操作,使系统立刻把修改的结果写到磁盘 
chattr +u file1 若文件被删除,系统会允许你在以后恢复这个被删除的文件 
lsattr 显示特殊的属性 


十二、打包和压缩文件 


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格式压缩包 


十三、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 返回包含所要搜索字符串的软件包名称 
 

十四、文本查看、处理


①、查看文件内容 

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"
set -i '/\/etc\/install.sh/d' 1.txt
/ 搜索
匹配\/etc\/install.sh,就是“/etc/install.sh”
-i 表示操作在源文件上生效.否则操作内存中数据,并不写入文件中.
在分号内的/d表示删除匹配的行。
 
举例2:
删除以a开头的行
sed -i '/^a.*/d' tmp.txt
^a表示开头是a, .*表示后跟任意字符串

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()|11
25 boolean com.dustpan.zeus.core.service.MergeService.executeGePrintSyncTask()|203
26 boolean com.dustpan.zeus.core.service.InitShopDateService.executeInitShopTask()|11
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()|33
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

十五、vim专题 

①、大小写转换

: vim大小写转换_郭耀今 -- 蓝天白云-CSDN博客_vim大写转小写

②、字符串处理专题

总结:

掐头(删左侧: ①#:删左侧;②##:贪婪删左侧)去尾(删右侧: ①%:删右边;②%%:贪婪删右侧)

1、linux shell 字符串操作详解 (长度,读取,替换,截取,连接,对比,删除,位置 )

2、Linux Bash Shell字符串截取

3、Shell 截取字符串

4、shell脚本字符串截取的8种方法

5. Linux-shell脚本字符串截取

6. linux中shell变量$#,$@,$0,$1,$2的含义解释/Shell中的${}、##和%%使用范例/export

7.Shell 命令中的特殊替换、模式匹配替换、字符串提取和替换

8.shell变量里的字符替换

字符串切片操作样例:

# 1. 从左边第几个字符开始,及字符的个数

url="https://www.baidu.com/"
echo ${url:0:5}

其中的 0 表示左边第一个字符开始,5 表示字符的总个数。
结果:https

# 2. 从左边第几个字符开始(下标从0开始),一直到结束
url="https://www.baidu.com/"
echo ${url:5}
结果:://www.baidu.com/

③、vi中文本操作

vi/vim 中在每行行首或行尾插入指定字符串

行首 :%s/^/your_word/
行尾 :%s/$/your_word/

按键操作:

注释(列模式方式):ctrl+v 进入列编辑模式,向下或向上移动光标,把需要注释的行的开头标记起来,然后按大写的I,再插入注释符,比如”#”,再按Esc,就会全部注释了。

删除:先按v,进入visual模式,横向选中列的个数(如”#”注释符号,需要选中两列),再按Esc,再按ctrl+v 进入列编辑模式,向下或向上移动光标,选中注释部分,然后按d, 就会删除注释符号(#)。

PS:当然不一定是shell的注释符”#”,也可以是”//”,或者其他任意的字符;vim才不知道什么是注释符呢,都是字符而已。

案例:

vim 列编辑模式

使用替换命令:

替换命令语法:

:[addr]s/源字符串/目标字符串/[option]

全局替换:

:%s/源字符串/目标字符串/g

参数说明:

  • [addr]——表示检索范围,省略时表示当前行。
    • "%":表示整个文件,同"1,$";
    • ".,$":从当前行到文件尾;
  • s:表示替换操作
  • [option]:表示操作类型
    • g:全局替换
    • c:表示进行确认
    • p:表示替换结果逐行显示(Ctrl+L恢复屏幕)
    • 省略option:默认仅对每行第一个匹配串进行替换
  • 如果在源字符串和目标字符串中有特殊字符,需要使用“\”转义

举例:

在全部内容的行首添加//号注释
:% s/^/\/\//g

在2~50行首添加//号注释
:2,50 s/^/\/\//g

在2~50行首删除//号
:2,50 s/^\/\///g

全局替换(全文替换、全部替换):

:%s/原字符/希望替换的字符/g

④、vim基础操作

在命令模式下:

1、填到指定行,如5

:5

2、跳到最后一行

G(shift + g)

3、跳到行首

gg

4、转到第N行,如第7行

7G

5、删除所有内容

A).使用shift+g转到最后一行

B).命令模式下输入:1,.d

引申:深处第3行到最后一行

A).使用shift+g转到最后一行

B).命令模式下输入:3,.d

6、删除光标所在字符

x

7、删除表过所在前的字符(大写X)

X

8、删除到下一个单词开头

dw

9、删除到本单词末尾

de

10、删除到本单词末尾包括标点在内

dE

11、删除到前一个单词

db

12、删除到前一个单词包括标点在内

dB

13、删除一整行

dd

14、删除光标位置到本行结尾

ud$

15、删除光标位置到本行开头

d0

在vim中 ,“.”当前行 ,“1,.”表示从第一行到当前行 ,“d”删除,3dd代表删除三行。

16、vim 统计单词匹配数量
 
:%s/hello world/&/gn 
上句统计hello world 在全文出现的次数

如果要统计从50行到100行,出现的次数,则使用: 
:50,100s/hello world//gn

⑤、shell脚本中的注释(单行注释/多行注释)

1、单行注释

"#" 置于行首位置

2、多行注释

A) 方式一

:<<!
# 需要注释的内容
! 

B) 方式二

if false; then
# 待注释的代码块
fi

C) 方式三

((0)) && {
# 待注释的代码块
}


十五、字符设置和文件格式转换 

dos2unix filedos.txt fileunix.txt 将一个文本文件的格式从MSDOS转换成UNIX 
unix2dos fileunix.txt filedos.txt 将一个文本文件的格式从UNIX转换成MSDOS 
recode ..HTML < page.txt > page.html 将一个文本文件转换成html 
recode -l | more 显示所有允许的转换格式 


十六、文件系统分析 


badblocks -v /dev/hda1 检查磁盘hda1上的坏磁块 
fsck /dev/hda1 修复/检查hda1磁盘上linux文件系统的完整性 
fsck.ext2 /dev/hda1 修复/检查hda1磁盘上ext2文件系统的完整性 
e2fsck /dev/hda1 修复/检查hda1磁盘上ext2文件系统的完整性 
e2fsck -j /dev/hda1 修复/检查hda1磁盘上ext3文件系统的完整性 
fsck.ext3 /dev/hda1 修复/检查hda1磁盘上ext3文件系统的完整性 
fsck.vfat /dev/hda1 修复/检查hda1磁盘上fat文件系统的完整性 
fsck.msdos /dev/hda1 修复/检查hda1磁盘上dos文件系统的完整性 
dosfsck /dev/hda1 修复/检查hda1磁盘上dos文件系统的完整性 


十七、初始化一个文件系统 


mkfs /dev/hda1 在hda1分区创建一个文件系统 
mke2fs /dev/hda1 在hda1分区创建一个linux ext2的文件系统 
mke2fs -j /dev/hda1 在hda1分区创建一个linux ext3(日志型)的文件系统 
mkfs -t vfat 32 -F /dev/hda1 创建一个 FAT32 文件系统 
fdformat -n /dev/fd0 格式化一个软盘 
mkswap /dev/hda3 创建一个swap文件系统 


十八、SWAP文件系统 

mkswap /dev/hda3 创建一个swap文件系统 
swapon /dev/hda3 启用一个新的swap文件系统 
swapon /dev/hda2 /dev/hdb3 启用两个swap分区 


十九、备份 

dump -0aj -f /tmp/home0.bak /home 制作一个 '/home' 目录的完整备份 
dump -1aj -f /tmp/home0.bak /home 制作一个 '/home' 目录的交互式备份 
restore -if /tmp/home0.bak 还原一个交互式备份 
rsync -rogpav --delete /home /tmp 同步两边的目录 
rsync -rogpav -e ssh --delete /home ip_address:/tmp 通过SSH通道rsync 
rsync -az -e ssh --delete ip_addr:/home/public /home/local 通过ssh和压缩将一个远程目录同步到本地目录 
rsync -az -e ssh --delete /home/local ip_addr:/home/public 通过ssh和压缩将本地目录同步到远程目录 
dd bs=1M if=/dev/hda | gzip | ssh user@ip_addr 'dd of=hda.gz' 通过ssh在远程主机上执行一次备份本地磁盘的操作 
dd if=/dev/sda of=/tmp/file1 备份磁盘内容到一个文件 
tar -Puf backup.tar /home/user 执行一次对 '/home/user' 目录的交互式备份操作 
( cd /tmp/local/ && tar c . ) | ssh -C user@ip_addr 'cd /home/share/ && tar x -p' 通过ssh在远程目录中复制一个目录内容 
( tar c /home ) | ssh -C user@ip_addr 'cd /home/backup-home && tar x -p' 通过ssh在远程目录中复制一个本地目录 
tar cf - . | (cd /tmp/backup ; tar xf - ) 本地将一个目录复制到另一个地方,保留原有权限及链接 
find /home/user1 -name '*.txt' | xargs cp -av --target-directory=/home/backup/ --parents 从一个目录查找并复制所有以 '.txt' 结尾的文件到另一个目录 
find /var/log -name '*.log' | tar cv --files-from=- | bzip2 > log.tar.bz2 查找所有以 '.log' 结尾的文件并做成一个bzip包 
dd if=/dev/hda of=/dev/fd0 bs=512 count=1 做一个将 MBR (Master Boot Record)内容复制到软盘的动作 
dd if=/dev/fd0 of=/dev/hda bs=512 count=1 从已经保存到软盘的备份中恢复MBR内容 


二十、光盘操作 

cdrecord -v gracetime=2 dev=/dev/cdrom -eject blank=fast -force 清空一个可复写的光盘内容 
mkisofs /dev/cdrom > cd.iso 在磁盘上创建一个光盘的iso镜像文件 
mkisofs /dev/cdrom | gzip > cd_iso.gz 在磁盘上创建一个压缩了的光盘iso镜像文件 
mkisofs -J -allow-leading-dots -R -V "Label CD" -iso-level 4 -o ./cd.iso data_cd 创建一个目录的iso镜像文件 
cdrecord -v dev=/dev/cdrom cd.iso 刻录一个ISO镜像文件 
gzip -dc cd_iso.gz | cdrecord dev=/dev/cdrom - 刻录一个压缩了的ISO镜像文件 
mount -o loop cd.iso /mnt/iso 挂载一个ISO镜像文件 
cd-paranoia -B 从一个CD光盘转录音轨到 wav 文件中 
cd-paranoia -- "-3" 从一个CD光盘转录音轨到 wav 文件中(参数-3) 
cdrecord --scanbus 扫描总线以识别scsi通道 
dd if=/dev/hdc | md5sum 校验一个设备的md5sum编码,例如一张 CD 


二一、网络 - (以太网和WIFI无线) 


ifconfig eth0 显示一个以太网卡的配置 
ifup eth0 启用一个 'eth0' 网络设备 
ifdown eth0 禁用一个 'eth0' 网络设备 
ifconfig eth0 192.168.1.1 netmask 255.255.255.0 控制IP地址 
ifconfig eth0 promisc 设置 'eth0' 成混杂模式以嗅探数据包 (sniffing) 
dhclient eth0 以dhcp模式启用 'eth0' 
route -n show routing table 
route add -net 0/0 gw IP_Gateway configura default gateway 
route add -net 192.168.0.0 netmask 255.255.0.0 gw 192.168.1.1 configure static route to reach network '192.168.0.0/16' 
route del 0/0 gw IP_gateway remove static route 
echo "1" > /proc/sys/net/ipv4/ip_forward activate ip routing 
hostname show hostname of system 
host www.example.com lookup hostname to resolve name to ip address and viceversa(1) 
nslookup www.example.com lookup hostname to resolve name to ip address and viceversa(2) 
ip link show show link status of all interfaces 
mii-tool eth0 show link status of 'eth0' 
ethtool eth0 show statistics of network card 'eth0' 
netstat -tup show all active network connections and their PID 
netstat -tupl show all network services listening on the system and their PID 
tcpdump tcp port 80 show all HTTP traffic 
iwlist scan show wireless networks 
iwconfig eth1 show configuration of a wireless network card 
hostname show hostname 
host www.example.com lookup hostname to resolve name to ip address and viceversa 
nslookup www.example.com lookup hostname to resolve name to ip address and viceversa 
whois www.example.com lookup on Whois database 

二二、JPS工具

jps(Java Virtual Machine Process Status Tool)是JDK 1.5提供的一个显示当前所有java进程pid的命令,简单实用,非常适合在linux/unix平台上简单察看当前java进程的一些简单情况。

    我想很多人都是用过unix系统里的ps命令,这个命令主要是用来显示当前系统的进程情况,有哪些进程,及其 id。 jps 也是一样,它的作用是显示当前系统的java进程情况,及其id号。我们可以通过它来查看我们到底启动了几个java进程(因为每一个java程序都会独占一个java虚拟机实例),和他们的进程号(为下面几个程序做准备),并可通过opt来查看这些进程的详细启动参数。

     使用方法:在当前命令行下打 jps(需要JAVA_HOME,没有的话,到改程序的目录下打) 。

jps存放在JAVA_HOME/bin/jps,使用时为了方便请将JAVA_HOME/bin/加入到Path.

$> jps
23991 Jps
23789 BossMain
23651 Resin


比较常用的参数:

-q 只显示pid,不显示class名称,jar文件名和传递给main 方法的参数
$>  jps -q
28680
23789
23651

-m 输出传递给main 方法的参数,在嵌入式jvm上可能是null

$> jps -m
28715 Jps -m
23789 BossMain
23651 Resin -socketwait 32768 -stdout /data/aoxj/resin/log/stdout.log -stderr /data/aoxj/resin/log/stderr.log

-l 输出应用程序main class的完整package名 或者 应用程序的jar文件完整路径名

$> jps -l
28729 sun.tools.jps.Jps
23789 com.asiainfo.aimc.bossbi.BossMain
23651 com.caucho.server.resin.Resin

-v 输出传递给JVM的参数

$> jps -v
23789 BossMain
28802 Jps -Denv.class.path=/data/aoxj/bossbi/twsecurity/java/trustwork140.jar:/data/aoxj/bossbi/twsecurity/java/:/data/aoxj/bossbi/twsecurity/java/twcmcc.jar:/data/aoxj/jdk15/lib/rt.jar:/data/aoxj/jd

k15/lib/tools.jar -Dapplication.home=/data/aoxj/jdk15 -Xms8m
23651 Resin -Xss1m -Dresin.home=/data/aoxj/resin -Dserver.root=/data/aoxj/resin -Djava.util.logging.manager=com.caucho.log.LogManagerImpl -

Djavax.management.builder.initial=com.caucho.jmx.MBeanServerBuilderImpl

sudo jps看到的进程数量最全

jps 192.168.0.77

列出远程服务器192.168.0.77机器所有的jvm实例,采用rmi协议,默认连接端口为1099

(前提是远程服务器提供jstatd服务)

注:jps命令有个地方很不好,似乎只能显示当前用户的java进程,要显示其他用户的还是只能用unix/linux的ps命令。

详细情况请参考sun官方文档。
http://java.sun.com/j2se/1.7.0/docs/tooldocs/share/jps.html

GO TOP INDEX ^ 
Microsoft Windows networks (SAMBA) 
nbtscan ip_addr netbios name resolution 
nmblookup -A ip_addr netbios name resolution 
smbclient -L ip_addr/hostname show remote shares of a windows host 
smbget -Rr smb://ip_addr/share like wget can download files from a host windows via smb 
mount -t smbfs -o username=user,password=pass //WinClient/share /mnt/share mount a windows network share

-b file            若文件存在且是一个块特殊文件,则为真
-c file            若文件存在且是一个字符特殊文件,则为真
-d file            若文件存在且是一个目录,则为真
-e file            若文件存在,则为真
-f file            若文件存在且是一个规则文件,则为真
-g file            若文件存在且设置了SGID位的值,则为真
-h file            若文件存在且为一个符合链接,则为真
-k file            若文件存在且设置了"sticky"位的值
-p file            若文件存在且为一已命名管道,则为真
-r file            若文件存在且可读,则为真
-s file            若文件存在且其大小大于零,则为真
-u file            若文件存在且设置了SUID位,则为真
-w file            若文件存在且可写,则为真
-x file            若文件存在且可执行,则为真
-o file            若文件存在且被有效用户ID所拥有,则为真

-z string          若string长度为0,则为真
-n string          若string长度不为0,则为真
string1 = string2  若两个字符串相等,则为真
string1 != string2 若两个字符串不相等,则为真

int1 -eq int2      若int1等于int2,则为真
int1 -ne int2      若int1不等于int2,则为真
int1 -lt int2      若int1小于int2,则为真
int1 -le int2      若int1小于等于int2,则为真
int1 -gt int2      若int1大于int2,则为真
int1 -ge int2      若int1大于等于int2,则为真

!expr              若expr为假则复合表达式为真。expr可以是任何有效的测试表达式
expr1 -a expr2     若expr1和expr2都为真则整式为真
expr1 -o expr2     若expr1和expr2有一个为真则整式为真

特殊变量

$0                 正在被执行命令的名字。对于shell脚本而言,这是被激活命令的路径
$n                 该变量与脚本被激活时所带的参数相对应。n是正整数,与参数位置相对应($1,$2…)
$#                 提供脚本的参数号
$*                 所有这些参数都被双引号引住。若一个脚本接收两个参数,$*等于$1$2
$@                 所有这些参数都分别被双引号引住。若一个脚本接收到两个参数,$@等价于$1$2
$?                 前一个命令执行后的退出状态, 常用于判断上一个命令的执行结果, 以辅助判断下游分支逻辑的执行
$$                 当前shell的进程号。对于shell脚本,这是其正在执行时的进程ID
$!                 前一个后台命令的进程号

二三、crontab调度器

①、语法

Linux下的任务调度分为两类:系统任务调度和用户任务调度。Linux系统任务是由 cron (crond) 这个系统服务来控制的,这个系统服务是默认启动的。用户自己设置的计划任务则使用crontab 命令。在CentOS系统中:

cat /etc/crontab

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed

前四行是用来配置crond任务运行的环境变量:
》第一行SHELL变量指定了系统要使用哪个shell,这里是bash;
》第二行PATH变量指定了系统执行命令的路径;
》第三行MAILTO变量指定了crond的任务执行信息将通过电子邮件发送给root用户,如果MAILTO变量的值为空,则表示不发送任务执行信息给用户;
》第四行的HOME变量指定了在执行命令或者脚本时使用的主目录。

用户定期要执行的工作,比如用户数据备份、定时邮件提醒等。用户可以使用 crontab 工具来定制自己的计划任务。所有用户定义的crontab 文件都被保存在 /var/spool/cron目录中。其文件名与用户名一致。

用户所建立的crontab文件中,每一行都代表一项任务,每行的每个字段代表一项设置,它的格式共分为六个字段:
》前五段是时间设定段;
》第六段是要执行的命令段

crontab表达式 格式如下:
minute hour day month week command

crontab用法与实例crontab用法与实例

在以上各个字段中,还可以使用以下特殊字符:

"*"代表所有的取值范围内的数字,如月份字段为*,则表示1到12个月;
"/"代表每一定时间间隔的意思,如分钟字段为*/10,表示每10分钟执行1次。
"-"代表从某个区间范围,是闭区间。如“2-5”表示“2,3,4,5”,小时字段中0-23/2表示在0~23点范围内每2个小时执行一次。
","分散的数字(不一定连续),如1,2,3,4,7,9。
注:由于各个地方每周第一天不一样,因此Sunday=0(第一天)或Sunday=7(最后1天)。

case: 每隔2分钟,删除指定目录下,创建时间超过10个小时的文件

*/2 * * * * /bin/sh -c "find /tmp/hadoop-hdfs/mapred/local -cmin +600 -type d -exec rm -rf {} \;" >> /var/lib/hadoop-hdfs/auto_remove_mr_output.out

二四、Shell编程相关

①、内置变量

1、declare

declare声明变量的使用,总结如下:
declare [+/-][选项] 变量名
选项:
   -:给变量添加类型属性
   +:取消变量的类型属性
  -a:将变量声明为数组型,-A将声明一个关联数组,俗称字典。  关联知识:Shell 数组与关联数组详解及实例代码(https://www.jb51.net/article/103915.htm
  -i:将变量声明为整型
  -x:将变量声明为环境变量
  -r:将变量声明为只读变量
  -p:查看变量的被声明的类型

declare -i 说明:

和 (())、let、$[] 不同,declare -i的功能非常有限,仅支持最基本的数学运算(加减乘除和取余),不支持逻辑运算(比较运算、与运算、或运算、非运算),所以在实际开发中很少使用。

declare -i m n ret
m=10
n=30

ret=$m+$n
echo $ret

ret=$n/$m
echo $ret

declare的作用域,只在函数内,出来后就失效了,如下:

#!/bin/bash

foo()
{
declare FOO="bar"
}

bar()
{
foo
echo $FOO
}

bar


 

②、数据结构

1、数组

Linux shell中数组的使用

数组有两种数据类型:

A). 一是数值类型;

B). 二是字符串类型.

虽然shell本身是弱类型的,但也可以这么区分。

数值类型的数组:一对括号表示数组,数组中元素之间使用“空格”来隔开。

  举个列子: 

  arr_number=(1 2 3 4 5);

字符串类型数组:同样,使用一对括号表示数组,其中数组中的元素使用双引号或者单引号包含,同样使用“空格”来隔开。

  arr_string=("abc" "edf" "sss"); 或者 arr_string=('abc' 'edf' 'sss');

#!/bin/bash
arr_number=(1 2 3 4 5)

# ①、获取数组长度
# 语法: ${#ARRAY_NAME[@|*]}
echo 'arr_number length ='${#arr_number[@]}
echo 'arr_number length ='${#arr_number[*]}

# ②、根据下标访问数组元素(注意:下标与java语法类似,从0开始)
# 2nd key's value
echo "2nd key's value ="${arr_number[1]}

# ③、分片访问
echo ${arr_number[@]:0:6}

# ④、模式替换
echo ${arr_number[@]/3/33}

# ⑤、数组的遍历
for e in ${arr_number[@]}
do
        echo $e
done

# ⑥、综合案例
# 编注:数组默认分割符为空格,如果数组元素中本身包含空格,也会被截断,这里通过改变IFS(系统字段分割# 符默认为空格)为换行,达到分割数组的目的。
greet=('hello world' "hi,john")
OLD_IFS=$IFS
IFS='\n'
for e in ${greet[@]}
do
        echo $e
done
IFS=$OLD_IFS

》①、批量删除日志:

for i in in {1..10}; do rm -f hadoop-cmf-hive-HIVEMETASTORE-nn1.testhdp.com.log.out.$i;done

》②、批量将日志置空:

for i in in {1..10}; do cat /dev/null > hadoop-cmf-yarn-NODEMANAGER-dn8.hadoop.com.log.out.$i;done

2、字典dict 或 Map

1). 声明字典类型:
declare -A dic

这里一定要-A来声明,-a只能用来声明数组类型。

2). 字典赋初值
dic=([key1]="value1" [key2]="value2" [key3]="value3")

3). 字典动态赋值
dic['key']=value

4). 打印指定key的value
echo ${dic['key']}

5). 打印所有key值
echo ${!dic[*]}

6). 打印所有value
echo ${dic[*]}

7). 遍历key值
for key in $(echo ${!dic[*]})
do
    echo "$key : ${dic[$key]}"
done
8). 综合案例

#! /bin/sh
#输入格式为一行一个单词

declare -A dict
dict=([k1]="v1" [k2]="v2")
echo ${dict["k1"]}
echo ${!dict[*]}
echo ${dict[*]}

for key in ${!dict[*]}
do
        echo "$key : ${dict[$key]}"
done
set -x
aa="null"
bb=
cc=''

#    -z 字符串为"null".就是长度为0.
#
#    -n 字符串不为"null"
#
#     注意:
#
#     使用-n在[]结构中测试必须要用""把变量引起来.使用一个未被""的字符串来使用! -z
#
#     或者就是未用""引用的字符串本身,放到[]结构中。虽然一般情况下可
#
#     以工作,但这是不安全的.习惯于使用""来测试字符串是一种好习惯.
if [ -n "$cc" ];then
        echo "aa is not null"
fi
set +x


#定义字典类型变量
declare -A dict

#从标准输入读取
while read word
do
    #若key为word的变量不存在,则为未定义,即第一次遇到此word,则将此word加入字典并设置其value为1。,否则自增value值
    if [ ! -n dict[${word}] ];then
        dict[${word}]=1
    else
        ((dict[${word}]++))
    fi
done
#打印统计结果
echo -e "word\t\tcount"
for key in $(echo ${!dict[*]})
do
    echo -e "$key\t\t${dict[$key]}"
done

综合案例二: shell的map简单的添加、查找、删除、遍历

3、管道输出中执行下一条指令

ps -ef | grep 'new-consumer' | awk '{print $2}' |xargs kill -9       #删除kafka consumer进程

ps -ef|grep java|grep -v grep|awk '{print $2}'|xargs kill -9          #删除java进程   

find /opt/flume-custom/ -name *.conf|xargs grep -re "127.0.0.1:9092" #查找到的文件中查找指定字符串

find /opt/ -type f -name '*.log' |xargs grep 'db.hostname'

cat ~/.ssh/id_rsa.pub | ssh my_admin@111.111.111.111 "cat - >> ~/.ssh/authorized_keys"

kill -9 $(ps -ef|grep "sh\ *start_new.sh\ *main"|grep -v grep|awk '{print $2}') #\ *表任意多空格

kill -9 `ps -ef|grep data-integration|awk '{print $2}'`

ls|while read f;do zip -r ${f}.zip $f;done  #压缩所有ls出来的文件夹

ls|grep 'hadoop-cmf-yarn-RESOURCEMANAGER-nn1.hadoop.com.log.out.[0-9]\{1,\}'|while read f;do cat /dev/null > $f;done #将所有RESOURCEMANAGER日志文件内容置为空,文件尾缀为1个以上从0到9的数字,如1、2、9、12均能匹配查找到,在nn1上磁盘(/var/log/{hadoop-hdfs,hadoop-yarn})上日志一般都比较大

# 查找10日前创建的文件,并情况其内容
find . -type f -name '*oozie-instrumentation.log.*' -atime +10 | while read f;do cat /dev/null > $f;done

#查看所有用户的crontab任务,其中"-I {}"参数,可以使用-i来等量实现
cat /etc/passwd | cut -f 1 -d : |xargs -I {} crontab -l -u {}
cat /etc/passwd | cut -f 1 -d : |xargs -i crontab -l -u {}

# 查询当前目录下所有文件(含目录下文件)中包含关键字(sku)的文件路径, 滤重, 并过滤掉路径中含指定字符(000)
grep -rn 'sku' * | awk -F ':' '{print $1}' | uniq | grep -v 000

注意:

xargs 的参数 “-n” 后接数字,表示一次传递几个参数给xargs

(pyspark) [david@cdh01 bin]$ echo '1 2 3 4'|xargs -n1
1
2
3
4
(pyspark) [david@cdh01 bin]$ echo '1 2 3 4'|xargs -n2
1 2
3 4
(pyspark) [david@cdh01 bin]$ echo '1 2 3 4'|xargs -n3
1 2 3
4
(pyspark) [david@cdh01 bin]$ echo '1 2 3 4'|xargs -n4
1 2 3 4

传送门:Shell基础知识》xargs详解

读取文件每一行,并循环做处理:

①、while read line
do
       …
done < file

②、cat file  | ${BIZ_LOGICAL}

综合实例:

ssh   127.0.0.1 <<EOF
sudo su
sed -i 's/^Hostname=.*/Hostname=127.0.0.1/' /etc/zabbix/zabbix_agentd.conf
cat /etc/zabbix/zabbix_agentd.conf | grep Hostname
ps -ef | grep zabbix | awk  '{print \$2}' | xargs kill -9 
/usr/sbin/zabbix_agentd -c /etc/zabbix/zabbix_agentd.conf
sleep 2
ps -ef  | grep zabbix
exit
exit
EOF

4、循环、迭代逻辑控制

4.1 while循环语法(while...do...done)

#hdfs文件统计

hdfs dfs -ls /  | hdfs dfs -ls `awk '{print $8}'`/ |  echo -e "`awk '{print $8}'`/ \n"  | while read line ; do echo -e "$line \t\t\t\t\t `sudo -u hdfs hdfs dfs -ls -R $line | wc -l `"    ;done

hdfs dfs -ls /  | hdfs dfs -ls `awk '{print $8}'`/ |  awk '{ cmd="echo -e  "$8"\\\t\\\t\\\t\\\t`sudo -u hdfs  hdfs dfs -ls -R  "$8"| wc -l`" ;cmd|getline ; print $0}'

#jar包里统计包含指定字符的文件名

ls;while read line;do cat /dev/null>$line; done

ls lib/* |while read line;do jar -tf $line|grep LogAnalysis; echo $line;done

#hdfs文件大小统计排序

hdfs dfs -du ${HDFS_PATH} | 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)}'

#获取所有java程序的进程号

ps -ef | while read line ; do if [[ $line =~ "java" ]] ;then echo $line |  awk -F ' ' '{print $2}' ; fi ;done

//循环所有文件,并添加header
#!/bin/bash
ls OrderDetail_sysdate_* |while read file;do
sed -i "1i\\$(cat header.csv)" $file
done

综合案例:

清理日志文件夹中的日志文件,将其置为黑洞文件内容(即情况该文件)。

#!/bin/bash

#先遍历本文件夹里文件夹
dir_list=`ls`

#对查询到的文件夹执行清空其内文件的操作
for dir in $dir_list;do
    echo $dir
    ls $dir/* | while read line;do echo $line; cat /dev/null > $line; done
done

for i in `seq 1 $(cat /proc/cpuinfo |grep "physical id" |wc -l)`; do dd if=/dev/zero of=/dev/null & done

pkill -9 dd

5、break 与 contine区别

如下代码所示:

不带参数 N:
break 循环只能退出最内层的循环;
continue 只能去掉本次循环的剩余代码;

带参数 N:
break N可以退出N层循环;
continue N 将会把N层循环剩余代码都去掉,单循环次数不变;
#!/bin/bash

for i in a b c d
do
    echo -n $i

    for j in `seq 10`
    do
        if test $j -eq 5;then
            #break
           # continue
            #break 2
            continue 2
        fi
        echo -n $j
    done

    #换行
    echo 
done

##########################################
###
### Program result:
###
##########################################
#
#>>>>>>>>>>>>>> 1. break >>>>>>>>>>>>>>>>>
# a1234
# b1234
# c1234
# d1234

#>>>>>>>>>>>>>> 2. continue >>>>>>>>>>>>>>>>>
# a1234678910
# b1234678910
# c1234678910
# d1234678910

#>>>>>>>>>>>>>> 3. "break 2","break 3" has same effect >>>>>>>>>>>>>>>>>
# a1234

#>>>>>>>>>>>>>> 4. "continue 2" >>>>>>>>>>>>>>>>>
# a1234
# b1234
# c1234
# d1234

6、大文件拆分处理

文件拆分:

split -d -a 8 -l 10000 PayOrderDetail.csv PayOrderDetail_sysdate_.csv

用法:

Usage: split [OPTION]... [INPUT [PREFIX]]
Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default
size is 1000 lines, and default PREFIX is 'x'.  With no INPUT, or when INPUT
is -, read standard input.

Mandatory arguments to long options are mandatory for short options too.
  -a, --suffix-length=N   generate suffixes of length N (default 2)
      --additional-suffix=SUFFIX  append an additional SUFFIX to file names
  -b, --bytes=SIZE        put SIZE bytes per output file
  -C, --line-bytes=SIZE   put at most SIZE bytes of lines per output file
  -d, --numeric-suffixes[=FROM]  use numeric suffixes instead of alphabetic;
                                   FROM changes the start value (default 0)
  -e, --elide-empty-files  do not generate empty output files with '-n'
      --filter=COMMAND    write to shell COMMAND; file name is $FILE
  -l, --lines=NUMBER      put NUMBER lines per output file
  -n, --number=CHUNKS     generate CHUNKS output files; see explanation below
  -u, --unbuffered        immediately copy input to output with '-n r/...'
      --verbose           print a diagnostic just before each
                            output file is opened
      --help     display this help and exit
      --version  output version information and exit

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

CHUNKS may be:
N       split into N files based on size of input
K/N     output Kth of N to stdout
l/N     split into N files without splitting lines
l/K/N   output Kth of N to stdout without splitting lines
r/N     like 'l' but use round robin distribution
r/K/N   likewise but only output Kth of N to stdout

GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
For complete documentation, run: info coreutils 'split invocation'

详细案例,详见:split命令_Linux split命令:切割(拆分)文件

7、awk

#批量删除hdfs下ods层下所有数据

hdfs dfs -lsr /user/hive/warehouse/ods|awk '{print "hdfs dfs -rm -R" $8}'

8、实现脚本中切换用户并执行该用户相关的命令操作

假如当前用户为root账户,希望切换到其他用户下执行相关的操作,如有以下业务场景:

想以yarn用户身份,取删除yarn运行相关的早期用处不大的日志。

方式①、

#!/bin/bash
su - yarn <<EOF
    pwd;
    exit;
EOF

方式②、

su - ${USER} -c ${COMMAND} > /dev/null 2>&1 &

注意:

该命令的执行权限是临时的,只在本条语句起作用。即在COMMAND命令行内部,是以$USER身份执行命令;执行结束后,回到初始状态用户,这里为root。 

案例:

## 01-Handle logic of clean HDFS NAMENODE & DATANODE & audit logs.
########################################################
su - hdfs -c '
        HDFS_PATH=/var/log/hadoop-hdfs;
        ls $HDFS_PATH | grep "hadoop-cmf-hdfs-NAMENODE-nn1.hadoop.com.log.out.[0-9]\{1,\}$" | while read f;     do `cat /dev/null > $HDFS_PATH/$f`; done   ;
        ls $HDFS_PATH | grep "hadoop-cmf-hdfs-DATANODE-nn1.hadoop.com.log.out.[0-9]\{1,\}$" | while read f;     do `cat /dev/null > $HDFS_PATH/$f`; done   ;
        ls $HDFS_PATH | grep "hdfs-audit.log.[0-9]\{1,\}$" | while read f;                                      do `cat /dev/null > $HDFS_PATH/$f`; done
'

注意:

① ls这段语句在命令行下执行没任何问题,提取到“su - hdfs -c”中时,`cat /dev/null > $HDFS_PATH/$f`这段必须要包裹上``符号,才能正常执行。

② -c 参数中,可以执行多行命令,但是需要几个条件:A). 所用命令使用''包裹,每一行命令间,使用";"来进行分隔。

补充su的用法:

[root@cdh-nn1 ~]# su --help

Usage:
 su [options] [-] [USER [arg]...]

Change the effective user id and group id to that of USER.
A mere - implies -l.   If USER not given, assume root.

Options:
 -m, -p, --preserve-environment  do not reset environment variables
 -g, --group <group>             specify the primary group
 -G, --supp-group <group>        specify a supplemental group

 -, -l, --login                  make the shell a login shell
 -c, --command <command>         pass a single command to the shell with -c
 --session-command <command>     pass a single command to the shell with -c
                                 and do not create a new session
 -f, --fast                      pass -f to the shell (for csh or tcsh)
 -s, --shell <shell>             run shell if /etc/shells allows it

 -h, --help     display this help and exit
 -V, --version  output version information and exit

For more details see su(1).

su 和 “su - ${USER}”的区别:

①、su只是切换用户。
②、su - 切换用户并切换shell环境。

③、su another
pwd后为/home/current

④、su - another
pwd后为/home/another

9、awk实现查找奇数行、偶数行:

seq 20 > test.txt
[root@server1 tmp]# awk 'NR%2 != 0' test.txt
[root@server1 tmp]# awk 'NR%2 == 0' test.txt

10、IFS专题

IFS, 全称 内部字段分隔符(Internal Field Separator, IFS) , 作用是在Linux中定义一个定界符,默认是空格。

如果字符串中的分隔符,默认不是空格,而是逗号(如csv文件), 则可以考虑临时替换IFS为逗号,处理完文本处理任务后, 再将默认的修改回来.

如果脚本实现, 按","提取表名list:

batch_upsert_table_process.sh

#!/bin/bash

include_tables="activity_info,activity_rule,activity_sku,base_category1,base_category2,base_category3,base_province,base_region,base_trademark,coupon_info,coupon_range,coupon_use,financial_sku_cost,sku_info,spu_info,user_info"

function get_element_by_split_comma(){
    ifs_old=$IFS
    IFS=","

    for tbl in $(echo "${include_tables}");do
        echo 'Now is handle table >>>>>>>>>>>>>>>>>>>>> '$tbl
        /data/maxwell/bin/maxwell-bootstrap --database gmall --table $tbl --config /data/maxwell/tf_custom_config/gmall_rtdw_test.properties
    done

    #Recovery IFS to default
    IFS=$ifs_old
}

get_element_by_split_comma

、echo在shell中控制颜色&闪烁显示

1、在shell中显示色彩

语法格式:

echo -e "\033[颜色1:颜色2m 要展示的文字 \033[0m"

参数说明:

-----------------------------------------------------------------------------------------------------------------------

-e选项:表示允许反斜杠(对字符)转义。
\033[颜色1;颜色2m:称为转义序列,它本身是一个整体,中间不要有空格。
\033[:转义序列的开始。其中\033代表Esc符号,也可以使用\E或\e来代替。
颜色1和颜色2:表示字体的前景色或背景色,至于颜色1和颜色2哪一个表示前景色,哪一个表示背景色,由其设定的数值来决定,前景色和背景色的数值空间是不同的。
m:转义序列的终止标志。
\033[0m:表示将颜色恢复回原来的配色。
 我们可以用一张原理图来理解:

-----------------------------------------------------------------------------------------------------------------------

图示说明:

颜色码:

④、数据类型转化

1、字符串转化为数字

案例1: 将日期中以0开头的数字字符串转换为数字

比如今日为2022-03-25, 如果想获取月份, 可以使用 echo $(date +%m) 或 echo `date +%m`, 将获取到字符串"03", 但我们想要去掉开头0的3, 翻遍date的api都没有找到.

这时候可以考虑使用数学运算将原字符串 与 一个数字0相加, 变相通过数学计算获取到整形的计算结果.

[hdfs@hadoop test]$ echo $(expr $(date +%m) + 0)
3

[hdfs@hadoop test]$ echo `expr $(date +%m) + 0`
3

[hdfs@hadoop test]$ hive --hivevar year=$(date +%Y) --hivevar month=`expr $(date +%m) + 0` -f /data/program/test_hive.hql

test_hive.hql中则可以使用上述动态传参的值:

ALTER TABLE ads.my_partition_table_test DROP IF EXISTS PARTITION(year=${hivevar:year}, month=${hivevar:month});

⑤、登录shell 与 非登录shell区别

登录shell:使用linux账户登录后执行的shell

非登录shell:不经登录,直接使用shell,如ssh 远程连接到主机后执行的shell

注意:

  •  如果将环境变量配置信息,配置在/etc/profile中,对于非登录shell,则获取不到。
  • 而对于/etc/profile.d/*.sh,则对于2种shell,都可以访问到。

二十五、程序开机自启动服务配置 


Centos系统服务器脚本目录位置:/usr/lib/systemd/

其内部有系统(system)和用户(user)2个文件夹,如需要开机不登录即要求能执行的程序,在系统服务(system)里,即/usr/lib/systemd/system;

而如果需要用户登录之后才可以运行的程序,在用户服务(user)里,即/usr/lib/systemd/user。

这里以nginx服务开启自启为例:

[Unit]    
Description=Nginx restart on Reboot
After=network.target    
     
[Service]    
Type=forking    
User=nginx
Group=nginx
ExecStart=/etc/init.d/nginx start    
ExecReload=/etc/init.d/nginx restart    
ExecStop=/etc/init.d/nginx  stop    
PrivateTmp=true    

[Install]    
WantedBy=multi-user.target   

参数说明:

  1. Description:描述服务
  2. After:描述本服务的上游依赖关系,即上游启动完毕后,才可以启动本服务
  3. [Service]服务运行参数的设置
  4. Type=forking是后台运行的形式
  5. User服务启动用户
  6. Group服务启动用户组
  7. ExecStart为服务的具体运行命令
  8. ExecReload为重启命令
  9. ExecStop为停止命令
  10. PrivateTmp=True表示给服务分配独立的临时空间

注意:

  • [Service]的启动、重启、停止命令全部要求使用绝对路径
  • [Install]服务安装的相关设置,可设置为多用户

一般文件以644权限进行保存,如下:

[root@nn2 system]# ll frp.service 
-rw-r--r-- 1 root root 266 Oct 29 11:50 frp.service

设置开机自启动命令:systemctl  enable  nginx.service

>> 如果查看systemctl启动服务的log信息?

Service启动之后, 如果想查询其详细日志信息, 可以使用类似tail的命令, 使用journalctl -f 可以来实时追踪日志. 

使用journalctl可以查看使用systemctl启动的service,常用参数有两种, 如下:

①. 显示多个混合在一起的systemctl 服务日志, 一般刚启动完一个service时查看比较方便

journalctl -f

②. 只查看某一个具体的service服务的日志

journalctl -u 服务名

如:
2021-11-10 10:06:37 nn1 systemd: Started Bigdata KafkaManager.
2021-11-10 10:06:37 nn1 kafka-manager: This application is already running (Or delete /opt/software/kafka-manager-1.3.3.23/RUNNING_PID file).
2021-11-10 10:06:37 nn1 systemd: bigdata_kafkaManager.service: main process exited, code=exited, status=255/n/a
2021-11-10 10:06:37 nn1 systemd: Unit bigdata_kafkaManager.service entered failed state.
2021-11-10 10:06:37 nn1 systemd: bigdata_kafkaManager.service failed.
2021-11-10 10:06:46 nn1 bigdata_admin: root [/etc/systemd/system]2021-11-10 10:06:46 systemctl is-enabled bigdata_kafkaManager.service
2021-11-10 10:06:52 nn1 systemd: Reloading.
2021-11-10 10:06:53 nn1 systemd: [/run/systemd/generator.late/cloudera-scm-server.service:13] Failed to add dependency on +cloudera-scm-server-db.service, ignoring: Invalid argument
2021-11-10 10:06:53 nn1 systemd: [/etc/systemd/system/bigdata_kafkaManager.service:15] Unknown lvalue 'StartLimitIntervalSec' in section 'Service'
2021-11-10 10:06:53 nn1 bigdata_admin: root [/etc/systemd/system]2021-11-10 10:06:52 systemctl disable bigdata_kafkaManager.service
2021-11-10 10:07:02 nn1 systemd: Stopped Bigdata KafkaManager.
2021-11-10 10:07:02 nn1 systemd: [/etc/systemd/system/bigdata_kafkaManager.service:15] Unknown lvalue 'StartLimitIntervalSec' in section 'Service'
2021-11-10 10:07:02 nn1 systemd: [/etc/systemd/system/bigdata_kafkaManager.service:15] Unknown lvalue 'StartLimitIntervalSec' in section 'Service'
2021-11-10 10:07:02 nn1 bigdata_admin: root [/etc/systemd/system]2021-11-10 10:07:02 systemctl stop bigdata_kafkaManager.service

③. 通过 "系统日志" 来进行查询

tail -100f /var/log/message

2021-11-10 10:06:37 nn1 systemd: Started Bigdata KafkaManager.
2021-11-10 10:06:37 nn1 kafka-manager: This application is already running (Or delete /opt/software/kafka-manager-1.3.3.23/RUNNING_PID file).
2021-11-10 10:06:37 nn1 systemd: bigdata_kafkaManager.service: main process exited, code=exited, status=255/n/a
2021-11-10 10:06:37 nn1 systemd: Unit bigdata_kafkaManager.service entered failed state.
2021-11-10 10:06:37 nn1 systemd: bigdata_kafkaManager.service failed.
2021-11-10 10:06:46 nn1 bigdata_admin: root [/etc/systemd/system]2021-11-10 10:06:46 systemctl is-enabled bigdata_kafkaManager.service
2021-11-10 10:06:52 nn1 systemd: Reloading.
2021-11-10 10:06:53 nn1 systemd: [/run/systemd/generator.late/cloudera-scm-server.service:13] Failed to add dependency on +cloudera-scm-server-db.service, ignoring: Invalid argument
2021-11-10 10:06:53 nn1 systemd: [/etc/systemd/system/bigdata_kafkaManager.service:15] Unknown lvalue 'StartLimitIntervalSec' in section 'Service'
2021-11-10 10:06:53 nn1 bigdata_admin: root [/etc/systemd/system]2021-11-10 10:06:52 systemctl disable bigdata_kafkaManager.service
2021-11-10 10:07:02 nn1 systemd: Stopped Bigdata KafkaManager.
2021-11-10 10:07:02 nn1 systemd: [/etc/systemd/system/bigdata_kafkaManager.service:15] Unknown lvalue 'StartLimitIntervalSec' in section 'Service'
2021-11-10 10:07:02 nn1 systemd: [/etc/systemd/system/bigdata_kafkaManager.service:15] Unknown lvalue 'StartLimitIntervalSec' in section 'Service'
2021-11-10 10:07:02 nn1 bigdata_admin: root [/etc/systemd/system]2021-11-10 10:07:02 systemctl stop bigdata_kafkaManager.service
2021-11-10 10:07:24 nn1 bigdata_admin: root [/etc/systemd/system]2021-11-10 10:07:08 watch free -g
2021-11-10 10:07:24 nn1 bigdata_admin: root [/etc/systemd/system]2021-11-10 10:07:08 watch free -g
2021-11-10 10:07:24 nn1 bigdata_admin: root [/etc/systemd/system]2021-11-10 10:07:08 watch free -g
2021-11-10 10:18:20 nn1 bigdata_admin: root [/etc/systemd/system]2021-11-10 10:08:19 tail -100f /var/log/messages

二十六、持续监控Linux命令的执行情况


watch -d -n 1 ls -l

参数说明:

①、-n:默认为2s刷新一次,通过-n 参数更新刷新频次;

②、-d:方便查看输出与上次的不同之处。

参考博文列表:

  1. Linux常用命令大全(非常全!!!) - fcyh - 博客园
  2. shell中break 与 continue - 亮哥vvv - 博客园
  3. crontab用法与实例 | 《Linux就该这么学》
  4. 最详细的CentOS7设置自定义开机启动服务教程 - 简书(centos7设置自定义开机启动)
  5. Centos7允许3306端口通过防火墙_vv小飞的专栏-CSDN博客_centos 允许端口(Centos7允许3306端口通过防火墙)
  6. Linux字符截取命令-cut_小工匠-CSDN博客(cut文本处理)
  7. 服务器日志 之 CentOS7日志管理工具 journalctl - 简书(服务器日志 之 CentOS7日志管理工具 journalctl)
  8. echo 在shell及脚本中显示色彩及闪烁警告效果 - 南清风 - 博客园(echo 在shell及脚本中显示色彩及闪烁警告效果)
  9. Linux命令大全(排版清晰!!持续更新!!非常详细)
  10. Linux sort命令详解
  • 257
    点赞
  • 2609
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值