Linux下文件查找与定位

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux下文件查找与定位相关的知识,希望对你有一定的参考价值。


Linux下一切皆文件,但是文件由于文件的属性的不同,在查找上可以针对不同的文件做相应的查找以便加快查询速度和减少资源的消耗。

 

1 .   which 命令【可执行文件的查找,系统文件中检索】:此命令是查找显示可执行命令的路径和别名,通过查找可以确定在/sbin /usr/sbin /usr/bin 、哪个目录下, 是在系统和用户环境变量中存在的目录文件中查找的。

 

参数

解释

--all,  -a

Print all matching executables in  PATH, not just the first.

 

--read-alias,  -i

 

 

Read aliases from stdin, reporting  matching ones on stdout. This is useful in combination with using an alias  for which itself. For example

           alias  which=alias | which -i.

 

--skip-alias

Ignore option `--read-alias, if  any. This is useful to explicity search for normal binaries, while using the  `--read-alias option in an alias or function for which.

 

--read-functions

Read shell function definitions  from stdin, reporting matching ones on stdout. This is useful in combination  with using a shell function for which itself.   For example:

       which() { declare -f | which  --read-functions [email protected] }

           export -f which

 

--skip-functions

Ignore option `--read-functions,  if any. This is useful to explicity search for normal binaries, while using  the `--read-functions option in an alias or function for which.

 

--skip-dot

Skip directories in PATH that start with a dot.

 

--skip-tilde

Skip directories in PATH that  start with a tilde and executables which reside in the HOME directory.

 

--show-dot

If a directory in PATH starts with  a dot and a matching executable was found for that path, then print  "./programname" rather than the full path.

 

--show-tilde

Output a tilde when a directory  matches the HOME directory. This option is ignored when which is invoked as  root.

 

--tty-only

Stop processing options on the  right if not on tty.

 

--version,-v,-V

Print version information on  standard output then exit successfully.

 

        

例子:

a.一般查找都是显示的绝对路径

[[email protected] ~]# which pwd

/bin/pwd

 

b.注意的是若是普通用户,查找一些只有root权限的命令是找不到的:

[[email protected] ~]$ whichuserdel

/usr/bin/which:nouserdelin(/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/user1/.local/bin:/home/user1/bin)

[[email protected] ~]$ su -

Password:

Last login: Sun Feb 26 10:20:33CST 2017 on pts/0

[[email protected] ~]# whichuserdel

/sbin/userdel

 

2  whereis 命令【可执行文件的查找,系统文件中检索】:此命令用于查找可执行文件,结果是输出二进制文件的位置,配置信息,手册页信息。是在系统和用户环境变量中存在的目录文件中查找的。

 

参数

解释

-b     

Search only for binaries.

 

-m

Search only for manuals.

 

-s

Search only for sources.

 

-u

Only show the command names that have  unusual entries.  A  command   is  said to be unusual if it  does not have just one entry of each explicitly requested type.  Thus ‘whereis -m -u *‘ asks  for those files in the current directory  which have no documentation file, or more than one.

-B list

Limit the places where whereis  searches   for  binaries,  by  a  whitespace-separated list of directories.

 

-M list

Limit   the  places  where   whereis  searches  for manuals, by awhitespace-separated list  of directories.

 

-S list

Limit the places where  whereis   searches  for  sources,   by  a whitespace-separated list  of directories.

 

-f

Terminates  the   directory  list and signals the  start of filenames.  It must be used  when any of the -B, -M, or  -S  options  is used.

-l

Output   list  of  effective   lookup paths the whereis is using. When non of -B, -M, or -S is  specified the option will out hard coded paths that the command was able to  find on system.

        

例子:

a. 显示sudo命令相关的 命令位置,命令的配置文件,命令的帮助手册

[[email protected] ~]# whereis sudo

sudo: /usr/bin/sudo /etc/sudo.conf /usr/share/man/man8/sudo.8.gz

 

b. 此命令不同于which的地方是: 此命令不受权限的控制,也就是什么二进制文件都能检索,而且输出的信息比which更详细!,值得注意的是:which是在/bin/sbin 目录下遍历出结果的,但是whereis是在/usr/bin/usr/sbin…目录下遍历出结果的,虽然/bin/sbin /usr/bin/usr/sbin)中的文件是完全一样的,但是在使用对象的权限上是不一样的,有时候更配置的默认路径是有关的。所以建议,在root下多用which,在普通用户下多用whereis

 

[[email protected] ~]$ whereis sudo

sudo: /usr/bin/sudo /etc/sudo.conf /usr/share/man/man8/sudo.8.gz

[[email protected] ~]$ whereis -b sudo

sudo: /usr/bin/sudo /etc/sudo.conf

[[email protected] ~]$ which sudo

/bin/sudo                            

[[email protected] ~]$ whereis -m sudo

sudo: /usr/share/man/man8/sudo.8.gz

[[email protected] ~]$ whereis -u sudo

sudo: /usr/bin/sudo /etc/sudo.conf /usr/share/man/man8/sudo.8.gz

[[email protected] ~]$

 

 

 

3.    whatis 命令【可执行文件的查找,数据库中检索】:此命令是在whatis数据库中搜索命令。Whatis数据库中包含了系统所有的命令的简单描述

 

 

参数

解释

-d,  --debug

Print  debugging information.

-v,  --verbose

Print  verbose warning messages.

-r,  --regex

Interpret  each name as a regular expression.  If  a  name   matches  any part  of a page name, a match will be made.  This option causes whati s to be somewhat  slower due to the nature of database searches.

 

-w,  --wildcard

Interpret  each name as a pattern  containing  shell   style  wildcards.

For  a match to be made, an expanded name must match the entire page name.  This option causes whatis to be  somewhat   slower  due  to   the  nature of database  searches.

-l,  --long

Do  not   trim  output to the terminal  width.  Normally, output will be  truncated to the terminal width to avoid  ugly   results  from  poorly written NAME sections.

-s  list, --sections list, --section list

Search  only the given manual sections.  list  is a colon- or comma-separated list of sections.  If an entry in list is a simple section,  forexample  "3",  then   the  displayed  list of descriptions will include pages in  sections "3", "3perl", "3x", and so on; while  if an entry  in list  has   an  extension, for example  "3perl", then the list will only

include  pages in that exact part of the manual section.

-m  system[,...], --systems=system[,...]

If  this system has access to  other  operating   system‘s  manual  page names, they can be accessed using this  option.  To search NewOS‘s manual page names, use the option -m NewOS. The system specified can be a  combination of comma delimited operatingsystem  names.    To  include a search of the  native operating system‘s manual page names, include the system name man in  the argument string. This option will override the $SYSTEM environment  variable.

-M  path, --manpath=path

Specify  an alternate set of colon-delimited manual page hierarchies to

search.  By default, whatis uses the  $MANPATH   environment  variable, unless it  is empty or unset, in which case it will determine an appropriate manpath based on your $PATH environment variable.  This   option overrides the contents of $MANPATH.

-L  locale, --locale=locale

whatis  will normally determine your current locale  by a call to the C function setlocale(3) which  interrogates  various   environment  varables,  possibly   including  $LC_MESSAGES  and   $LANG.  To temporarily override  the determined value, use this   option  to  supply   a  locale string  directly   to  whatis.  Note that it will not take effect until the  search for pages actually begins.   Output such as the help messagewill always be displayed in the  initially determined locale.

-C  file, --config-file=file

Use  this   user  configuration file rather  than the default of ~/.man path.

 

 

例子:

a. whatis 的作用就是输出系统命令简单的描述信息,一般用的有点少。注意的是它不具有输出自定义的命令的功能

[[email protected] ~]$ whatis ls

ls (1)               - list directory contents

ls (1p)              - list directory contents

[[email protected] ~]$ su -

Password:

Last login: Sun Feb 26 12:04:01 CST2017 on pts/0

[[email protected] ~]# whatis ls

ls (1)               - list directory contents

ls (1p)              - list directory contents

[[email protected] ~]#

 

4.    apropos 命令【查找可执行文件,数据库中检索】:此命令可以搜索在whatis数据库中的字符串,为关键字输出一组数据库文件包含的系统命令的简短描述(例如要完成某项任务,但是又不知道哪些命令,就可以用apropos了,当然也可以用man-k参数来完成)。注意的是:若系统命令增加了,则需要更新数据库(update whatis),这样才能准确!

 

参数同于whatis

例子:

 

[[email protected] ~]# man mkdir

[[email protected] ~]# man -k mkdir

gvfs-mkdir (1)       - Create directories

mkdir (1)            - make directories

mkdir (1p)           - make directories

mkdir (2)            - create a directory

mkdir (3p)           - make a directory

mkdirat (2)          - create a directory relative to adirectory file descriptor

[[email protected] ~]# apropos mkdir

gvfs-mkdir (1)       - Create directories

mkdir (1)            - make directories

mkdir (1p)           - make directories

mkdir (2)            - create a directory

mkdir (3p)           - make a directory

mkdirat (2)          - create a directory relative to adirectory file descriptor

 

 

5.    locate命令【查找普通文件,数据库中检索】:此命令用于快速查找文件和档案,其工作依赖于一个事先建立好的数据库,这个数据库会每天更新一次,保证文件的准确性。因此locate的使用可能不准确,但是在使用前可以先手动更新数据库update,然后使用就准确了!

 

参数

解释

-A, --all

Print only  entries that match all PATTERNs instead of   requiring  only one of them to  match.

-b, --basename

Match  only the base name against the specified  patterns.  This is the opposite of  --wholename.

-c, --count

Instead of  writing file names on standard output, write the number  of  matching entries only.

-d, --database  DBPATH

Replace  the   default  database  with DBPATH.  DBPATH is a :-separated list of database  file names.  If more than one  --database option is specified, the  resulting  path is a concatenation of  the separate paths. An empty database file name is replaced by the  default   database.  Adatabase  file name - refers to the standard  input.  Note that a database can be read from the standard input  only once.

-e, --existing

             

 

Print only  entries that refer to files existing at the time locate  is

run.

-L, --follow

When  checking whether files exist (if the  --existing option is specified), follow trailing symbolic links.  This   causes  broken  symbolic links to be omitted from the  output. His is  the  default behavior.The opposite can be specified  using--nofollow.

-h, --help

Write a summary  of the available options to standard output   and  exit successfully.

-i,  --ignore-case

Ignore case  distinctions when matching patterns.

-l, --limit, -n  LIMIT

Exit  successfully after finding LIMIT entries.  If the --count option is specified, the  resulting count is also limited to LIMIT.

-m, --mmap

Ignored, for  compatibility with BSD and GNU locate.

-P, --nofollow,  -H

When checking  whether files exist (if the --existing option is  specified), do not follow trailing symbolic  links.  This causes broken symbolic  links to be reported like other files.This is the opposite of --follow.

-0, --null

Separate the  entries on output using the ASCII NUL   character  instead of writing  each entry on a separate line.  This  option is designed for interoperability with the --null option of GNU  xargs(1).

-S, --statistics

Write statistics  about each read database to standard   output  instead of searching for  files and exit successfully.

-q, --quiet

Write  no messages about errors encountered while  reading and process ing databases.

-r, --regexp  REGEXP

Search for a  basic regexp REGEXP.  No PATTERNs  are   allowed  if  this option is used, but this option can be  specified multiple times.

--regex

Interpret all  PATTERNs as extended regexps.

-s, --stdio

Ignored, for  compatibility with BSD and GNU locate.

-V, --version

Write  information about the version and license  of locate on standard output and exit successfully.

-w, --wholename

Match only the  whole path name against the specified patterns.

This is the  default behavior. The opposite can be specified  using

--basename.

 

 

例子:

 

 

 

a.      查找含有iptables的所有文件

[[email protected] ~]$ locate iptables

/etc/sysconfig/iptables-config

/usr/bin/iptables-xml

/usr/sbin/iptables

/usr/sbin/iptables-restore

/usr/sbin/iptables-save

/usr/share/augeas/lenses/dist/iptables.aug

/usr/share/bash-completion/completions/iptables

/usr/share/doc/iptables-1.4.21

/usr/share/doc/iptables-1.4.21/COPYING

/usr/share/doc/iptables-1.4.21/INCOMPATIBILITIES

/usr/share/man/man1/iptables-xml.1.gz

/usr/share/man/man8/iptables-extensions.8.gz

/usr/share/man/man8/iptables-restore.8.gz

/usr/share/man/man8/iptables-save.8.gz

/usr/share/man/man8/iptables.8.gz

/usr/share/mime/text/x-iptables.xml

/usr/src/kernels/3.10.0-514.el7.x86_64/include/config/ip/nf/iptables.h

/usr/src/kernels/3.10.0-514.el7.x86_64/include/config/ip6/nf/iptables.h

 

b.      统计含有iptables的文件的个数(行数)

[[email protected] ~]$ locate -c iptables

18

 

c.      若有临时文件的建立,再查找此临时文件,必须手动更新数据库

[[email protected] ~]$ cd data/;mkdir aaaaaaaaa  AAAAAAAAAAAA

[[email protected] data]$ ls

aaaaaaaaa  AAAAAAAAAAAA

[[email protected] data]$ locate -r "aaaaaaa*"

[[email protected] data]$ locate -r "AAAAAAAAAA*"

此时系统内已经有了目标文件,但是locate依赖的数据库还未更新,所以检索不到(-r是匹配正则表达式的参数),接下来更新数据库

[[email protected] data]$ updatedb

updatedb: can not open a temporary file for`/var/lib/mlocate/mlocate.db‘

此处提示权限不够!切换到root下刷新

[[email protected] data]$ su -

Password:

Last login: Sun Feb 26 14:29:17 CST 2017 on pts/0

[[email protected] ~]# updatedb

[[email protected] ~]# su - user1

Last login: Sun Feb 26 14:29:30 CST 2017 on pts/0

接下来就可以locate文件了

[[email protected] ~]$ locate -r "aaaaaa*"

/home/user1/data/aaaaaaaaa

[[email protected] ~]$ locate -r "AAAAAAAAAAA*"

/home/user1/data/AAAAAAAAAAAA

 

注意的是:(-i代表的是不区分大小写的参数)-r参数必须是参数的最后一个!

[[email protected] ~]$ locate -ri "aaaaaaa*"

locate: non-option arguments are not allowed with --regexp

[[email protected] ~]$ locate -ir "aaaaaaa*"

/home/user1/data/AAAAAAAAAAAA

/home/user1/data/aaaaaaaaa

[[email protected] ~]$ locate -rc "aaaaa*"

locate: non-option arguments are not allowed with --regexp

[[email protected] ~]$ locate -cr "aaaaa*"

2

 

 

6.    find 命令【普通文件查找,在文件系统中检索】:此命令将文件系统内的目标文件列出,参数很多,可以指定文件名,类别,时间,大小,权限等不同的信息及其组合来检索文件!

 

命令格式:               find  [路径]      [选项]    [-exec| -ok  command {} \; ]

命令解释:  -exec(不交互)和-ok(交互)一样,{} \;表示的是将输出的内容交给command来处理

 

参数

解释

-name

按照文件名来查找

-perm

按照文件权限来查找

-user

按照文件的用户来查找

-group

按照文件的组来查找

-atime n

在过去n天内被访问过(access_time)的文件,n表示天数,-n表示过去的n天内,+n表示过去的n天前,n表示确定的日期(过去的第n天)

-ctime n

在过去n天内被更改过(change_time)的文件,n表示天数,同上

-amin n

在过去n分钟内被访问过(access_time)的文件,n表示分钟数,同上

-cmin n

在过去n分钟内被更改过(change_time)的文件,n表示分钟数,同上

-size n[ckMG]

按文件大小查找,n表示大小,+n表示大于n的文件,-n表示小于n的文件,c表示字节,k表示kBM代表MBG表示GB

-newer f1

查找更新时间比f1近的文件

-anewer f1

查找访问时间比f1早的文件

-empty

查找空文件,可以是目录或文件

-type

按照文件类型来查找

-fstype

按照文件系统来查找

-nogroup

查找无属组的文件

-nouser

查找无用户的文件

-uid

按照文件所属用户的UID查找

-gid

按照文件所属组的GID查找

-inum

按照文件的inode节点号查找

-readable

只匹配可读文件

-samefile

查找indode相同的文件

-writale

匹配可写文件

-links

按照文件链接数查找

-depth

使查找在进入子目录查找前先查找完本目录

-mount

查找文件时不跨越文件系统mount

-cpio

备份查找到的文件

-cpio    %;

按照文件系统来查找文件,一般文件系统在/etc/fstab文件中有记录

-prune

忽略某个目录

 

 

 

文件类型:

字符

解释

b

块设备文件

c

字符设备文件

d

目录文件

l

链接文件

f

普通文件

p

管道文件

s

套接字文件

 

 

例子:

a.  /home/user1/data目录中找出有a字符的文件并删除

a.1

[[email protected] data]$ ls

aaaaaaaaa  AAAAAAAAAAAA  sssss

[[email protected] data]$ ls aaaaaaaaa/

file11  file14

[[email protected] data]$ find ./ -name "*a*" | rm -r

rm: missing operand

Try ‘rm --help‘ for more information.

提示报错说rm没有操作对象,原因是rm不能接收从标准输入传来的数据!(不能接收标准输入数据的还有:)

[[email protected] data]$ find ./ -name "*a*" |xargs  rm –r

[[email protected] data]$ ls

AAAAAAAAAAAA  sssss

[[email protected] data]$

a.2方法二:注意删掉后会有提示!

[[email protected] data]$ ls

aaaaa  AAAAAAAAAAAA  sssss

[[email protected] data]$ ls aaaaa/

file1  file2

[[email protected] data]$ find ./ -name "*a*" -exec rm -r {} \;

find: ‘./aaaaa’: No such file or directory

[[email protected]ocalhost data]$ ls

AAAAAAAAAAAA  sssss

 

 

b.      使用混合方式查找文件,查找当前目录下大于1M并且在1天前访问过的文件(-and是与关系;-or是或关系)

[[email protected] ~]# find /etc/ -size +1M -and -atime +1

/etc/selinux/targeted/active/policy.kern

/etc/selinux/targeted/contexts/files/file_contexts.bin

/etc/selinux/targeted/policy/policy.30

/etc/gconf/schemas/ekiga.schemas

/etc/brltty/zh-tw.ctb

注意的是: find会受目标文件的权限的限制,普通用户在查找某些只有root才有访问权限的文件时,会报错:

[[email protected] ~]$ find /etc/ -size +10M -and -atime +1

find: ‘/etc/pki/CA/private’: Permission denied

find: ‘/etc/pki/rsyslog’: Permission denied

find: ‘/etc/dhcp’: Permission denied

find: ‘/etc/lvm/archive’: Permission denied

find: ‘/etc/lvm/backup’: Permission denied

find: ‘/etc/lvm/cache’: Permission denied

find: ‘/etc/selinux/targeted/active’: Permission denied

 

c.      使用权限-perm参数时候注意:-007代表的是最少权限为007的文件,而007代表的是权限就是007的文件(也就是所有用户都可以读写执行的文件);-100代表的是权限最小是100的文件(就是所属用户可执行文件)。

[[email protected] data]$ ll

total 0

-------rwx 1 user1 user1 0 Feb 26 16:28 file1

---x------ 1 user1 user1 0 Feb 26 16:28 file2

-rw-rw-r-- 1 user1 user1 0 Feb 26 16:29 file3

[[email protected] data]$ find ./ -perm 007

./file1

[[email protected] data]$ find ./ -perm -007

./file1

[[email protected] data]$ find ./ -perm 100

./file2

[[email protected] data]$ find ./ -perm -100

./

./file2

[[email protected] data]$

 

 

d.      无错误提示查找:若查找报错,则将错误信息信息扔掉(/dev/null文件相当于Windows中的垃圾箱,不同的是任何文件放到此目录下都将被瞬间清空,所以此目录也是空目录!),若查找正确,则打印出结果

[[email protected] data]$ find ./ -nam "aaa"

find: unknown predicate `-nam‘

[[email protected] data]$ find ./ -nam "aaa" 2>/dev/null

 

 

 

小结:

 

命令

检索文件

检索对象

显示内容

效能

which

$PATH中的文件/bin,/sbin

命令,二进制文件

绝对路径

Root用户使用最方便,普通用户使用时有时会有权限问题

whereis

$PATH中的文件/usr/bin,/usr/sbin

命令,二进制文件

绝对路径,配置文件路径,帮助文档路径

任何用户都可使用,无权限问题

whatis

whatis数据库

系统命令

目标命令简介

速度快,但是要建立临时数据库,消耗要高一点

apropos

whatis数据库

系统命令

一组相关命令简介

速度快,但是要建立临时数据库,消耗要高一点,得到一组简介

locate

索引数据库

文件

目标文件列表

速度快,但是索引数据库每天自动更新,有时候不具有时效性

find

文件系统

文件

目标文件列表

功能强大,常用作前提条件,为后续操作做铺垫!

 

 


本文出自 “11929788” 博客,请务必保留此出处http://11939788.blog.51cto.com/11929788/1901388

以上是关于Linux下文件查找与定位的主要内容,如果未能解决你的问题,请参考以下文章

linux实战项目经验得到的常用linux命令文件定位和内容查找

Linux查找定位文件命令

linux下目录与文件的查找

Linux中如何在指定目录下查找文件?

Linux下4个查找命令whichwhereislocatefind的总结

Linux服务器查找大文件