在 Linux 服务器上排查问题时,最常见的操作就是“找文件”——配置文件在哪、日志写在哪、某个库装没装。但面对几十万个文件的文件系统,盲目翻目录等于大海捞针。Linux 提供了三把利器:find(按条件搜索)、locate(数据库秒搜)、grep(文件内容搜索),配合使用可以几秒钟定位任何文件。
本文以查找 nginx.conf 配置文件为线索,逐一演示这三种方法,并附带按时间、大小、权限等条件查找的进阶用法。
操作环境:CentOS 7,Terminal SSH。
第一种:文件名查找
在服务器任意目录下输入 find / -name nginx.conf
[root@VM-0-10-centos ~]# find / -name nginx.conf
/usr/local/nginx/conf/nginx.conf
/root/lnmp1.7/lnmp1.7/conf/nginx.conf
/root/lnmp1.7/conf/nginx.conf
输出到终端的地址可以打开验证一下是否为正确文件。
或者使用locate命令 locate nginx.conf
[root@VM-0-10-centos ~]# locate nginx.conf
/root/lnmp1.7/conf/nginx.conf
/root/lnmp1.7/lnmp1.7/conf/nginx.conf
/usr/local/nginx/conf/nginx.conf
/usr/local/nginx/conf/nginx.conf.default
/usr/local/nginx/conf/nginx.conf_bak
第二种:关键字查找
在某一目录下输入该命令find / -name ‘nginx.*’
这里的*可以是确切目录,比如说usr,或者是etc目录,加快检索速度。
[root@VM-0-10-centos ~]# find /* -name '*nginx.*'
/etc/systemd/system/nginx.service
/etc/systemd/system/multi-user.target.wants/nginx.service
/home/wwwroot/wordpress/wp-content/uploads/2021/02/what-is-nginx.png
/root/lnmp1.7/lnmp1.7/init.d/nginx.service
/root/lnmp1.7/lnmp1.7/conf/nginx.conf
/root/lnmp1.7/lnmp1.7/include/upgrade_nginx.sh
/root/lnmp1.7/lnmp1.7/include/nginx.sh
/root/lnmp1.7/init.d/nginx.service
/root/lnmp1.7/conf/nginx.conf
/root/lnmp1.7/include/upgrade_nginx.sh
/root/lnmp1.7/include/nginx.sh
/root/code-server-3.9.0-linux-amd64/lib/vscode/extensions/markdown-language-features/node_modules/highlight.js/lib/languages/nginx.js
/usr/local/nginx/conf/nginx.conf
/usr/local/nginx/conf/nginx.conf_bak
/usr/local/nginx/conf/nginx.conf.default
/usr/local/nginx/logs/nginx.pid
/usr/local/qcloud/YunJing/YDVulner/yhvs/lib/info/web2/nginx.so
/usr/share/augeas/lenses/dist/nginx.aug
第三种:根据文件特征值查找
这里需要使用者了解具体参数,比如说文件大小,或者是修改时间,这样更能加快检索。
find / -amin -10 # 查找在系统中最后10分钟访问的文件
find / -atime -2 # 查找在系统中最后48小时访问的文件
find / -empty # 查找在系统中为空的文件或者文件夹
find / -group cat # 查找在系统中属于groupcat的文件
find / -mmin -5 # 查找在系统中最后5分钟里修改过的文件
find / -mtime -1 #查找在系统中最后24小时里修改过的文件
find / -nouser #查找在系统中属于作废用户的文件
find / -user fred #查找在系统中属于FRED这个用户的文件
补充:用 grep 搜索文件内容
前面都是按文件名查找。如果忘了文件名、但记得文件里写了什么内容,用 grep 按内容反查:
# 在 /etc 目录下搜索包含 "server_name" 的所有文件
grep -r "server_name" /etc/nginx/ 2>/dev/null
# 只显示文件名,不显示匹配行
grep -rl "server_name" /etc/nginx/
# 大小写不敏感搜索
grep -ri "Server_Name" /etc/nginx/
-r 递归搜索子目录,-l 只输出文件名,-i 忽略大小写。2>/dev/null 是过滤掉“权限不足”的报错信息。
实用技巧:find + grep 组合使用效率最高——先用 find 圈定文件范围,再用 grep 精确匹配内容:
# 找最近 7 天修改过的 .conf 文件,然后搜索其中包含 "fastcgi" 的行
find /etc/nginx/ -name "*.conf" -mtime -7 | xargs grep -n "fastcgi"
最后,对于nginx.conf的查找,我们可以直接使用nginx -t
[root@VM-0-10-centos ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
结果出现OK以及successful时候,那么这里的/usr/local/nginx/conf/nginx.conf即为我们要查找内容。
© 2021 Linux中查找文件 ·
本文由 Charlie 原创撰写,发布于 sodebug.com。
未经授权禁止转载、洗稿、机器抓取。AI 训练数据使用需获得书面授权。