Linux find directories in current directory

Содержание
  1. How To Find a Directory On Linux Based System
  2. How to find a directory on Linux
  3. Linux find directory command
  4. Finding a directory
  5. Dealing with “Permission denied error messages” on Linux
  6. How to find a directory named Documents on Linux?
  7. Getting a detailed list of files/dirs
  8. How do I list only directories?
  9. How do I perform a case insensitive search?
  10. How do I find a directory called project.images?
  11. A note about locate command
  12. Linux / UNIX List Just Directories Or Directory Names
  13. Display or list all directories in Unix
  14. Linux list only directories using ls command
  15. Linux Display or list only files
  16. Task: Create bash shell aliases to save time
  17. Use find command to list either files or directories on Linux
  18. Putting it all together
  19. 40 Best Examples of Find command in Linux
  20. Find files and Directories
  21. Find specific files by name or extension
  22. Looking for specific files in another directory
  23. Search for files by extension
  24. Find files and directories by name
  25. Find files or directories only
  26. Case insensitive find command
  27. Search for a file from multiple directories
  28. Find multiple files with different extensions from all directories
  29. Find files containing certain text
  30. Find Files and Directories Based on Size
  31. Find files of a certain size – equal to 30MB
  32. Find files larger than a specified size
  33. Find files less than 10MB in the current directory
  34. Find files with sizes between 100-200MB
  35. Look for directories larger than 20kb
  36. Find empty files and directories.
  37. Find files by age or modification time
  38. By modification date
  39. Find files based on access or modification
  40. Find files modified within the last n days
  41. Find files modified within a specific period.
  42. Files and directories accessed within the last 10 minutes
  43. Find files matching specific permissions
  44. Find files with permission 777
  45. Find files writable by the owner
  46. Find files owned by a user
  47. Find specific files owned by a user
  48. Find and list files and directories together with their permissions
  49. Find and act on the results
  50. Find files and change permissions
  51. Find and change file and directory permissions
  52. Find and copy files or directories
  53. Find and copy one file to many directories
  54. Find and move files to a different directory
  55. Find certain files and move to a specific different folder
  56. Find and move files based on age
  57. Find and delete files and directories
  58. Find and delete specific files only
  59. Remove both files and directories
  60. Delete by extension
  61. Find and delete files older than n days
  62. Find and delete directories only
  63. Find and remove empty files
  64. Find and remove empty directories
  65. What’s next?

How To Find a Directory On Linux Based System

I just switched from MS-Windows server admin to Debian Linux server system administration roles. I need to find a directory called project.images. I was also told that the locate command is the simplest and quickest way to find the locations of files and directories on Linux. But the locate command is not working out for me. How do I find project.images directory using command-line options only?

Tutorial details
Difficulty level Easy
Root privileges No
Requirements find command on Linux or macOS/Unix
Est. reading time 5m

You need to use find command. It is used to locate files on Linux or Unix-like system. The locate command will search through a prebuilt database of files generated by updatedb.

The find command will search live file-system for files that match the search criteria.

How to find a directory on Linux

The find command syntax is:
find /where/to/look/up criteria action
find /dir/path/look/up criteria action
find /dir/path/look/up -name «dir-name-here»
find /dir/path/look/up -name «pattern»
find /dir/path/look/up -name «dir-name-here» -print
find /dir/path/look/up -name «dir-name-here»
find / -name «dir-name-here»
find / -type d -name «dir-name-here»
find / -type d -name «dir-name-here» 2>/dev/null

Linux find directory command

The following example will show all files in the current directory and all subdirectories:

Finding a directory

To find a directory called apt in / (root) file system, enter:

Alert: When searching / (root) file system, you need to run the find command as root user.

Dealing with “Permission denied error messages” on Linux

Find will show an error message for each directory/file on which you don’t have read permission

How to find a directory named Documents on Linux?

Type the following command to search for Documents directory in your $HOME dir:
$ find $HOME -type d -name Documents
Sample outputs:

Getting a detailed list of files/dirs

Pass the -ls to list current file in ls command output format:

How do I list only directories?

Just find directories and skip file names pass the -type d option as follows:

Replace -name option with -iname as follows:

The patterns ‘apt’ match the directory names ‘apt’, ‘APT’, ‘Apt’, ‘apT’, etc.

How do I find a directory called project.images?

Type any one of the following command:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

A note about locate command

See also
  • All find command examples from our /faq/ sections.
  • Find command man page

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Why don’t you run updatedb and then locate and again you’ll have “simplest and quickest way to find the locations of files and directories on Linux”.

updatedb will update your database.

That only helps for semi-permanent files since it only checks periodically to update the updatedb database. For files that were created recently it will not be found.

Find is a great tool that i use a lot.
You could have talk about the -exec switch wich allows you to process the outpout. ie : find and delete all file in ./ that haven’t been modified since 90 day:

Anyway, great job on this website, keep it on!

I have to second that updatedb is the way to go for a novice linux user. No worries about syntax and whatnot. Its also very useful for when you need to do multiple scans since you only traverse the filesystem once.

In regards to -exec, you should be using -execdir when available due to some security implications… and the above rm -rf is somewhat dangerous since find by default traverses from the top down. Delete would be a much safer (and faster!!) operation than-exec rm.

I have to agree with your update, rm -Rf is maybe too dangerons to use for novice users.

I did not know -execdir wich seems to be very usefull.

Thank you for that update =)

Great article. so useful. since I don’t have root, I get very verbose “no permission” output that is useless and I have to find the actual location through all the muck. Is there a way to only print found paths? Thanks so much for this article!

All those “no permission” messages should be on stderr while the information you want is on stdout. Both stderr and stdout default to printing on the controlling terminal. Tacking “> stdoutfile” on the end of the command would separate them, leaving all the unwanted noise on the terminal and putting the good stuff in stdoutfile. It would make more sense to redirect stderr to /dev/null (throwing it away) and leaving the useful output on the controlling terminal, but that would require finding the instructions for redirecting stderr in the shell docs (again).

To avoid seeing stderr messages, just use something like this:

Источник

Linux / UNIX List Just Directories Or Directory Names

You can use combination of ls command, find command, and grep command to list directory names only. You can use the find command too. In this quick tutorial you will learn how to list only directories in Linux or UNIX.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux, macOS, or Unix terminal
Est. reading time 5 minutes

Display or list all directories in Unix

Type the following command:
$ ls -l | grep `^d’
$ ls -l | egrep `^d’
Or better try the following ls command only to list directories for the current directory:
$ ls -d */
Sample outputs:

Fig.01: List Directories in Unix and Linux Systems

Linux list only directories using ls command

Run the following ls command:
ls -d */

Listing only directories using ls command in Linux or Unix-like systems

Linux Display or list only files

Type the following command to display list only files in Linux or Unix:
$ ls -l | egrep -v ‘^d’
$ ls -l | egrep -v ‘^d’
The grep command is used to searches input. It will filter out directories name by matching first character ‘ d ‘. To reverse effect i.e. just to display files you need to pass the -v option. It invert the sense of matching, to select non-matching lines.

Task: Create bash shell aliases to save time

You can create two aliases as follows to list only directories and files.
alias lf=»ls -l | egrep -v ‘^d'»
alias ldir=’ls -d */’
##alias ldir=»ls -l | egrep ‘^d'»
Put above two aliases in your bash shell startup file:
$ cd
$ vi .bash_profile

Append two lines:
alias lf=»ls -l | egrep -v ‘^d'»
alias ldir=’ls -d */’
#alias ldir=»ls -l | egrep ‘^d'»
Save and close the file in vim. Now just type lf – to list files. Again run ldir to list directories only:
$ cd /etc
$ ldir
Sample outputs:

List directory names only:
$ cd /etc
$ ldir

Sample outputs:

Use find command to list either files or directories on Linux

The find command can be used as follows to list all directories in /nas, enter:

Pass the -maxdepth 0 to limit listing to the starting-points i.e. the current working directory only:
find /path/to/dir -maxdepth 1 -type d
find . -maxdepth 1 -type d
find . -maxdepth 1 -type d -ls

Listing only directories using the find command in Linux

Putting it all together

Say you want to find all directories ending with .bak extension and delete it, run the following find command in the current directory:
find . -type d -iname «.bak» -delete
Verify it:
find . -type d -iname «.bak» -ls
The following shell script does two things for Apache/Nginx/Lighttpd Webroot such as /webroot/:

  1. First, finds all files and directories and set permission to read-only for security reasons.
  2. Second, it allows our web server to read files regardless of permission so that we don’t get an HTTP/403 error.

In other words, all write permissions are removed from Webroot. The server/web-app can only read files but can not alter any files or upload any files. It helps reduces attack surfaces provided that you configure the rest of the server and web application firewall correctly.

Источник

40 Best Examples of Find command in Linux

Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.

The Linux find command is a powerful tool that enables system administrators to locate and manage files and directories based on a wide range of search criteria. It can find directories and files by their name, their type, or extension, size, permissions, etc.

Besides locating files and directories, combining the find command with others enables you to take action on the results. Adding the -exec option enables sysadmins to run external commands and perform actions like copying, moving, deleting, or changing permissions of the files matching the specified criteria such as size, name, etc.

In this article, we will start by explaining the basic Linux find commands with examples. This will show you how to find files and directories. We will then show you how to use the -exec option to act on the files or directories based on their size, permissions, etc.

The general syntax for the find command is

  • path specifies the directory.
  • name-of file or dir-to-search : Name of the file or directory to look for
  • action-to-take : such as copy, delete, move, etc.

In this tutorial, we will explain how to locate files and directories matching specified patterns. We will also see how to perform actions on the files or directories that the find command locates. The guide is based on Ubuntu but is applicable to most Linux distributions and versions.

Find files and Directories

Find specific files by name or extension

To look for a specific file, run the following command from the root (/). The command contains the exact name for the file you are searching for.

Please note that the results include the path. This is important if you don’t know the directory where the file is located, or when it is in more than one place.

You can also search for the file in another directory while still in the current location. In this case, you need to provide the path for the directory where you want to search.

Looking for specific files in another directory

In our case, we will look for all those starting with the letters file in the test directory.

Search for files by extension

To find a file in Linux with a certain extension, add it to the command.

Find files and directories by name

Use the command below to look for files and directories starting with the letters qa . In our computer, we have the qatree.txt and qa.txt files as well as a directory by the name qa .

If we run the command;

It returns the following output

The command returns both the files and directories matching the search criteria. To find files or directories only, you need to specify this in the command.

Find files or directories only

For files only, use the type f switch.

Files only

Directories only

Add the type d option to locate directories only.

Case insensitive find command

All searches with -name switch are case sensitive and will not give results with capital letters. To get all cases, use the -iname option.

Search for a file from multiple directories

To find the files in different directories, add their paths in the command. In our case, we will check in the test and numeric directories.

Find multiple files with different extensions from all directories

You can use the find command to locate multiple files that share the different extensions such as *.doc , *.txt *.pdf , etc. This can be done separately, one extension at a time, or using just one command that includes all the desired extensions.

find . -type f ( -name «*.txt» -o -name «*.pdf» -o -name «*.doc» )

Find files containing certain text

Sometimes, you want to access a file containing certain text but cannot recall its file name or location. This command allows you to find all the files containing your target text.

To look for all the files containing the word hyperconvergence”, use;

The –i option enables the command to ignore cases and will find the text whether capitalized or not i.e. hyperconvergence, Hyperconvergence , etc.

To look for the files in a specific directory, simply add them to the command

Find Files and Directories Based on Size

You can find all files or directories that are smaller, equal or greater than a certain size, within a certain range or empty. Use the appropriate size format depending on the type of files or directories you are searching for.

Size options include;

Find files of a certain size – equal to 30MB

To Search find all 30MB files

Find files larger than a specified size

Find files less than 10MB in the current directory

Find files with sizes between 100-200MB

When looking for files within a specific range such as between 100 and 200 MB

Look for directories larger than 20kb

find / -type d -size +20k

Find empty files and directories.

Files

find ./ -type f -size 0

Directories

Find files by age or modification time

Find files older than n days

The -mtime +8 will look for txt files that are older than 8 days.

By modification date

This will look for files modified within the last 17 hours

Looks for directories modified within the last 10 days

Find files based on access or modification

Find files based on date or time accessed. This allows you to see files that have or haven’t been accessed within a specified period.

To see files that have not been accessed within the last 10 days in the home directory.

Files accessed exactly 10 days ago

Accessed within the last 10 days

Find files modified within the last n days

You can also look for the files in the /home directory modified within the last 10 days using the command;

Find files modified within a specific period.

For example, all files modified between 6 and 15 days ago in the home directory.

Files and directories accessed within the last 10 minutes

To find the files accessed within the last 10 minutes, use the -amin option.

Directories accessed within the last 10 minutes

Find files matching specific permissions

Where mode is the permission which is either numeric such as 644, 655, 700, 777 , etc, or letters such as u=x, a=r+x, etc.

You can specify the mode in the following three different ways.

  1. Without a prefix when you want to find files with the exact permissions specified.
  2. With “ — “ for files with at least the specified permission. This returns files with the specified as well as additional higher permissions.
  3. Using “ / ” requires specifying the owner or group with the permission to the file.

Find files with permission 777

Find files with at least 766
find -perm -766

The command looks for all files in which the

  • The file owner has read/write/execute permissions.
  • Group has read/write permissions
  • Others have read/write permission

As such, it returns two files that meet this criterion – file1 and file2. The files do not need to have the exact 766 permissions and can have additional ones as long but must have at least the specified.

Find files writable by the owner

We will now use the “ / ” to looks for files writable by either their owner, or group, or others.

The above looks for files that are writable by either their owner or group.
This returns files that are writable by either but not necessarily both. To see files, where both have writable permissions, use the – prefix.

Find files owned by a user

Find all files owned by Jack

Find specific files owned by a user

Find all text files owned by Jack

Find and list files and directories together with their permissions

Find and act on the results

In this section, we will look at how you can act on the files that match the pattern specified in the find command.

Find files and change permissions

Find and change permissions of certain file types. In our case, we will work with PHP files with different permissions as shown below.

We will now look for all the PHP files (above) and replace their permissions with 755

The command looks for PHP files in the ver directory and then sets their permission to 755 ( rwxr-xr-x )

Find and change file and directory permissions

Find files with 644 permissions and change them to have 655 permissions

You can also look for directories with 644 permissions and replace this with 755.

The docs folder has 644 permissions

To set it to 755 , we run

Now we can check again to see what exactly 755

From above we can see the root and docs directories have the 755 permissions.

Ls –la command gives the following details

Find and copy files or directories

Find and copy a specific file to a directory

The command below will find the file22.tx t file and copy it to the

Find and copy one type of files to a directory

To find files such as images with jpg extension in the current directory and copy them to a different location like an images folder, use;

This will find and copy all the jpg files to the

Find and copy one file to many directories

Find and copy a single to multiple directories.

This will find the file hci file and copy it to the three directories of /tmp/dir1/ /tmp/dir2/ and $HOME/3/

Find and move files to a different directory

To move a known file from a directory to another. To move the universal.php file;

Search and move files with a certain extension to a different folder

Find certain files and move to a specific different folder

The command looks for all the files with names starting with uni and having any extension. It then moves them to the directory /unifiles/

Find and move files based on age

Find and move files older than specified days to a different location such as the archive.

This will look for pdf files older than 20 days and move them to the backup1 directory.

Find and delete files and directories

The syntax for finding and removing files or directories in the current directory is

find . -type f -name «file to delete» -exec rm -f <> ; to delete files only or

find . -type d -name «dir-to-delete» -exec rm -rf <> ; to delete directories only

Find and delete specific files only

To find and delete files starting with til, use;

To find and delete directories starting with til

Remove both files and directories

This will remove both files and directories starting with the letters til.

Delete by extension

Below is how you can locate and delete all txt files in the current directory. Replace the txt with another extension such as bak , pdf or any other that you want to remove.

In case you want the system to prompt you to confirm before deleting each file, add the -i option as below.

By default, the -rm will not remove the directories and you need to use the –r option to ensures a recursive removal. This ensures the deletion of empty directories and those containing files. The -f option forces the removal and is used for both the files and directories.

Find and delete files older than n days

Find and delete backup files older than 20 days from the current directory.

This will delete all .bak files older than 20 days.

Find and delete directories only

To delete a directory called dir22

Ensure that you match the directory name case or use the -iname option.

Removes both Dir22 and dir22

To confirm before deletion, use the -i option.

Output
rm: remove directory ‘./Dir22’? n
rm: remove directory ‘./dir22’? y

In our case, we typed n for directory Dir22 which will not be deleted and y for the dir22 which will now be removed.

Find and remove empty files

You can use any of the following commands to locate empty files and delete them automatically.

or
find ./ -type f -size 0 | xargs rm -f
or
find ./ -type f -size 0 –delete

Find and remove empty directories

To remove empty directories we will use the d option.

Another alternative is to use delete instead of remove.

Please note that deleting system or critical files from your computer can damage the operating system or applications or lead to loss of your important data.

To avoid accidental deletions, it is best practice to use a non-root user account. Also, ensure that you are deleting the right files that are not useful and that you have a backup of all your data files just in case.

What’s next?

Go ahead and try the above Linux find commands in your lab or NON PRODUCTION environment. See if you can use some to automate the file system cleanup with Crontab. And, to master Linux, check out this online course.

Источник

Читайте также:  Эмулятор андроид для кали линукс
Оцените статью