Remove any file linux

How to delete and remove files on Debian Linux

Command to delete and remove files on Debian Linux

The syntax is as follows for the rm and unlink command to remove files on Debian Linux:

  1. Open the Debian terminal application (bash shell)
  2. Type any one of the following command to delete a file named joey.db in the current directory
  3. rm joey.db
    OR
    unlink joey.db

Let use see all the rm command options to delete and remove files on Debian Linux.

Delete multiple files

Type the following command to delete the file named hannah.doc, vince.jpg, and dance.jpg located in the current directory:
vivek@debian-9-stretch:

$ rm hannah.doc vince.jpg dance.jpg
You can specify path too. If a file named hannah.doc located in /tmp/ directory, you can run:
vivek@debian-9-stretch:

$ rm /tmp/hannah.doc
vivek@debian-9-stretch:

$ rm /tmp/hannah.doc /home/vivek/dance.jpg /home/vivek/data/vince.jpg

  • 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

Debian Linux delete a file and prompt before every removal

To get confirmation before attempting to remove each file pass the -i option to the rm command on Debian Linux:
vivek@debian-9-stretch:

$ rm -i filename1
vivek@debian-9-stretch:

Force rm command on Debian Linux to explain what is being done with file

Pass the -v option as follows to get verbose output on Debian Linux box:
vivek@debian-9-stretch:

$ rm -v filename1
vivek@debian-9-stretch:

$ rm -v cake-day.jpg

Debian Linux delete all files in folder or directory

You need to pass the following options:
vivek@debian-9-stretch:

$ rm -rf dir1
vivek@debian-9-stretch:

$ rm -rf /path/to/dir/
vivek@debian-9-stretch:

$ rm -rf /home/vivek/oldschoolpics/
It will remove all files and subdirectories from a directory. So be careful. Always keep backups of all important data on Debian Linux.

Debian Linux delete file begins with a dash or hyphen

If the name of a file or directory or folder starts with a dash ( — or hyphen — ), use the following syntax:
vivek@debian-9-stretch:

$ rm — -filename1
vivek@debian-9-stretch:

$ rm — —filename1
vivek@debian-9-stretch:

$ rm -rf —directory1
vivek@debian-9-stretch:

$ rm ./-file
vivek@debian-9-stretch:

$ rm -rf ./—directory1

Do not run ‘ rm -rf / ‘ command as an administrator/root or normal Debian Linux user

rm -rf (variously, rm -rf /, rm -rf *, and others) is frequently used in jokes and anecdotes about Debian Linux disasters. The rm -rf / variant of the command, if run by an administrator, would cause the contents of every writable mounted filesystem on the computer to be deleted. Do not try these commands on Debian Linux :
vivek@debian-9-stretch:

$ rm -rf /
vivek@debian-9-stretch:

Conclusion

And there you have it, the rm command which is used to removes each given FILE Debian Linux operating systems. Please note that rm does not remove directories by default. You need to pass the -r option as described above. To see all available options for the rm command type the following man command:
rm —help
OR
man rm

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

Источник

Linux Delete All Files In Directory Using Command Line

Linux Delete All Files In Directory

The procedure to remove all files from a directory:

  1. Open the terminal application
  2. To delete everything in a directory run: rm /path/to/dir/*
  3. To remove all sub-directories and files: rm -r /path/to/dir/*
Читайте также:  Windows 10 облачная переустановка

Let us see some examples of rm command to delete all files in a directory when using Linux operating systems.

How to remove all the files in a directory?

Suppose you have a directory called /home/vivek/data/. To list files type the ls command:
$ ls

Understanding rm command option that deleted all files in a directory

  • -r : Remove directories and their contents recursively.
  • -f : Force option. In other words, ignore nonexistent files and arguments, never prompt. Dangerous option. Be careful.
  • -v : Verbose option. Show what rm is doing on screen.

Deleting hidden vs non-hidden files

In Linux, any file or directory that starts with a dot character called a dot file. It is to be treated as hidden file. To see hidden files pass the -a to the ls command:
ls
ls -a
ls -la
To remove all files except hidden files in a directory use:
rm /path/to/dir/*
rm -rf /path/to/dir/*
rm *
In this example, delete all files including hidden files, run:
rm -rf /path/to/dir1/<*,.*>
rm -rfv /path/to/dir1/

  • 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

Bash remove all files from a directory including hidden files using the dotglob option

If the dotglob option set, bash includes filenames beginning with a ‘.’ in the results of pathname expansion. In other words, turn on this option to delete hidden files:

See GNU/bash man page for the shopt command online here:
man bash
help shopt

Linux Remove All Files In Directory

As I said earlier one can use the unlink command too. The syntax is:
unlink filename
For example, delete file named foo.txt in the current working directory, enter:
unlink foo.txt
It can only delete a single file at a time. You can not pass multiple files or use wildcards such as *. Therefore, I strongly recommend you use the rm command as discussed above.

Conclusion

In this quick tutorial, you learned how to remove or delete all the files in a directory using the rm command. Linux offers a few more options to find and delete files. Please see the following tutorials:

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

Источник

Linux / Unix: Find And Remove Files With One Command On Fly

However, the rm command does not support search criteria. For example, find all “*.bak” files and delete them. For such necessities, you need to use the find command to search for files in a directory and remove them on the fly. You can combine find and rm command together. This page explains how to find and remove files with one command on fly.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements find command
Est. reading time 4 minutes

Find And Remove Files With One Command On Fly

The basic find command syntax is as follows:
find dir-name criteria action
Where,

  1. dir-name : – Defines the working directory such as look into /tmp/
  2. criteria : Use to select files such as “*.sh”
  3. action : The find action (what-to-do on file) such as delete the file.

You want to remove multiple files such as ‘*.jpg’ or ‘*.sh’ with one command find, try:
find . -name «FILE-TO-FIND» -exec rm -rf <> \;
OR
find /dir/to/search/ -type f -name «FILE-TO-FIND-Regex» -exec rm -f <> \;
The only difference between above two syntax is that the first command remove directories as well where second command only removes files. Where, options are as follows:

  • 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

  1. -name «FILE-TO-FIND» : File pattern.
  2. -exec rm -rf <> \; : Delete all files matched by file pattern.
  3. -type f : Only match files and do not include directory names.
  4. -type d : Only match dirs and do not include files names.

Modern version of find command has -delete option too. Instead of using the -exec rm -rf <> \; , use the -delete to delete all matched files. We can also explicitly pass the -depth option to the find to process each directory’s contents before the directory itself. It is also possible to use the -maxdepth option to control descend at most levels of directories below the starting-points. For example, -maxdepth 0 means only apply the tests and actions to the starting-points themselves. Similary, we can pass the -mindepth to the find. It means do not apply any tests or actions at levels less than levels (a non-negative integer). For exampe, -mindepth 1 means process all files except the starting-points. So here is a simplied syntax:
find /dir/to/search/ -type f -name «FILES-TO-FIND» -delete
find /dir/to/search/ -type f -name «FILES-TO-FIND» -depth -delete
find /dir/to/search/ -maxdepth 2 -type f -name «FILES-TO-FIND» -depth -delete

Examples of find command

Find all files having .bak (*.bak) extension in the current directory and remove them:
find . -type f -name «*.bak» -exec rm -f <> \;
OR
find . -type f -name «*.bak» -delete
Find all core files in the / (root) directory and remove them (be careful with this command):
# find / -name core -exec rm -f <> \;
### OR ###
# find / -name core -delete
Find all *.bak files in the current directory and removes them with confirmation from user:
$ find . -type f -name «*.bak» -exec rm -i <> \;
Sample outputs:

The -delete always works better because it doesn’t have to spawn an external process such as rm for every matched file. However, the -delete option may not available on all find versions. Hence, we can use the xargs command as follows too:
find . -type f -name «*.err» -print0 | xargs -I <> -0 rm -v «<>»

Where the find command option is as follows:

  • -print0 – Force find command to print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs.

And the xargs command options are as follows:

  • -I <> : Replace occurrences of <> in the initial-arguments with names read from standard input. We pass <> as arg to the rm command.
  • -0 : Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end of file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode.
  • rm -v «<>« : Run rm command on matched files.

Conclusion

Read the following man pages using the man command:
man find
man xargs
man rm
For detailed information on find command please see finding/locating files with find command part # 1, Part # 2.

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

Источник

How to Remove Files and Directories in Linux?

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

One of the basic file system administration tasks involves creating, modifying, and deleting different types of files and directories. Knowing some basic tools and concepts for file deletion comes in handy and can save you time.

Linux offers several tools that can help us accomplish file removal tasks. Often we need to remove not just a single, but a bunch of files and directories, based on some criteria. It is helpful to know a few common commands and their combinations to get our task done easily.

  • Use the below commands with caution especially the ones which use regular expressions or some search patterns with the find command. An incorrect expression or pattern may delete essential data/system files or simply non-intended files.
  • Always secure the latest backup of important data and system files.
  • Take caution before running such commands especially when running it with Sudo or as superuser (root).

Not so popular. To remove a single file permanently, we can use unlink command.

Remove single file

There’s a more commonly used command for removing files, i.e., rm command, which supports removing one or more files simultaneously.

rm prompts you to confirm file deletion for files that are write-protected else it proceeds to directly remove the file. To make rm always prompt before deleting a file, use -i flag:

rm command deletes without displaying any messages on the screen. To list what rm command is actually doing, use rm with -v flag.

To remove write-protected files without prompting for confirmation, use -f flag.

Remove multiple files

Multiple files can be removed by specifying multiple filenames to rm as arguments.

rm also supports regular expressions. If you want to delete all files named file-name-* , you can use:

We can also specify multiple files using regular expressions. If we want to delete three files that match file-name-1 , file-name-2 and file-name-3 , we can use something like:

Remove directory

An empty directory can be deleted using rm command with -d option.

Options supported for file removal can also be combined with directory removal using -d flag as well. For example:

To delete a directory that is non-empty use -r flag.

If you don’t want any prompts before deleting the directory and its contents, use -rf flag. This WILL delete everything inside the directory including the directory itself without any confirmation. Do use caution while using it especially as root.

Find and remove files

For more complex requirements, we can use the find command with different options. To remove all files matching pattern inside a path given by

If we want to remove anything that matches a pattern including directories inside , we can slightly modify the above command as:

Modern versions of the find command support the delete function internally. Here -delete flag replaces rm command while -depth instructs find command to first process the contents of the directory before the directory itself :

The above example is more efficient when working with a large number of files as it doesn’t spawn a new external process for rm command for each matched file. But not all versions of find command (yet) may support -delete flag. As an alternate, we have the option to use xargs command with find as shown in the next example below:

Or use exec command’s + terminator to chain together everything found by find command like xargs:

By default, the find command uses -print flag which we usually skip writing. With xargs , we need to avoid new-line character between each filename. As such -print0 flag instructs find to print null character after every found filename.

Similarly, we specify -0 flag with xargs so that both commands couple up. rm command here deletes the file passed on to by piped find input. For example, the below command will search and remove all *.tmp files from the current user’s home directory (given by

find command offers several ways to search files and directories including ownership, permission, timestamp, etc. We’ll be covering a few such ways that can help us in specific file removal tasks.

Find and remove files by a user

To delete everything inside a given directory owned by a specific user , use:

In the above example, -mindepth flag with value 1 prevents the directory given by from deletion if it matches the find pattern and criteria. Or to delete everything inside a given directory belonging to a particular group , use:

If you do not want to traverse the sub-directories under the search path, you also have the option to use -maxdepth with appropriate directory depth value.

Here’s an example run:

If you want to specify user-id and group-id instead, you can try something like:

Find and remove empty directories

To delete all empty directories inside a given path , you can use:

Instead, to delete all empty files inside a given path , use:

Find and remove files older than X

Sometimes, you may need to delete files older than x days. find has options to read file’s creation ( ctime ), access ( atime ) and modification ( mtime ) times. We can use mtime option with find to find and delete files modified more than x days ago.

For instance, to delete all files with extension log inside /var/tmp with a modification time of 30 days ago or more, we can use:

Find and remove files by permission

Now, we can also delete files based on some specific permission, like:

Or if we want to use a symbolic form for permission, use:

Summing Up

Linux offers unlink , rm and rmdir commands that are simple and can be easily extended with the use of regular expressions. For more advanced needs, you have the option to use a combination of tools like find and xargs to achieve what you need. Other than the examples in this article, you’ve got the option to use find with any of its available flags to customize your search. Refer man pages for respective commands to learn more about them.

Always run find commands without rm or -delete flag and analyze its output to know which files or directories will be impacted by the execution of an actual command. Having proper backup configuration and policy helps not only in case of accidental deletions but also in cases of hardware failures and cyber-attacks.

Источник

Читайте также:  Виснет панель задач windows 10
Оцените статью