Linux下常用命令
1.查看进程
#grep -v 代表过滤 ps -ef|grep java|grep -v grep
2.更改文件权限
#更改文件所有者 chown -R user.group file #更改文件读写全些 chmod ... file
3.使用awk批量杀进程
#假设杀所有java进程 ps -ef|grep java|grep -v grep|awk '{print "kill -9 " $2}' | sh
4.使用top和awk批量查看进程
把下面脚本存成shell执行即可
#!/bin/bash PIDS=$(ps -ef|grep redis|grep -v grep|awk '{print $2}' | sed 's/^/-p/') top $PIDS
5.使用rpm查看/安装/卸载包(centos/redhat)
#查看安装包 rpm -ql | grep mysql #安装 rpm -ivh mysql.rpm #查看安装位置 rpm -ql mysql包名(可用查看安装包命令先查看) #卸载安装包 [--nodeps] 表示不检查依赖,强制卸载 rpm -e [--nodeps] 包名
6.设置服务开机自启动
#先需要把服务(可执行sh)放到/etc/init.d/下 chkconfig 服务名 on/off
#CentOS 7 以上版本
systemctl enable vsftpd.service
7.批量删除文件
> 7.1 固定大小
find . -name "*" -type f -size 20c|xargs -n 1 rm -f
> 7.2 删除固定时间之前的文件
#!/bin/bash # 设置要清理的目录,这里使用当前目录 DIR="/home/www/crm/logs" # 设置文件修改时间阈值,这里是7天 DAYS=14 # 查找并删除旧文件 find "$DIR" -type f -mtime +$DAYS -exec rm -f {} \; # 查找并删除空目录(如果需要) find "$DIR" -type d -empty -exec rmdir {} \;
把上面那个文件保存为脚本 , 比如 a.sh
然后使用crontab -e 编辑 , 每天1点执行
0 1 * * * /home/www/bin/a.sh
8.出现^M结尾的文件 , 或者.sh 无法执行的问题
#把build.sh中的换行符,全部替换掉 sed -i 's/\r$//' build.sh
9.查找文件(文件名)
#一般查找 find / -name 文件名 #带通配符查找 find / -name "*文件名*"
10.查找文件内容
#-r 目录查找 #-n 显示行号 #-i 忽略大小写 grep -rn "minimal" /etc/
11.windows文件转到linux下多了^M (问题同8)
具体报错为 : /bin/sh^M: bad interpreter: No such file or directory
sed -i -e 's/\r$//' x.sh
12.压缩与解压
#压缩文件 gz tar zcvf fileName.tar.gz DirName #解压文件 gz tar zxvf fileName.tar.gz
#压缩文件 bz2 tar jcvf fileName.tar.bz2 DirName #解压文件 bz2 tar jxvf fileName.tar.bz2
13.时间同步命令
#可通过yum直接安装 yum -y install ntpdate
#同步时间 ntpdate 172.18.0.227 #每天23点自动同步 0 23 * * * ntpdate 172.18.0.227 >> /var/log/ntpdate.log
14. 批量替换文件内容
sed -i "s/原字符/新字符/g" `grep 原字符 -rl /文件路径`
15.软连接 (Linux中的创建快捷方式)
ln -s 源文件 目标文件(快捷方式位置)
16.scp传输文件
# 如果是目录 , 就加上-r参数 scp 源文件用户名@源文件IP:源文件路径 目标文件用户名@目标文件IP:目标文件路径
另一种传输方式 , 需要先安装 rsync , 可试用 yum install -y rsync
rsync -avz /path/to/local/file username@remote_host:/path/to/remote/directory