- Unix Command to Delete all files in a directory but preserve the directory
- 8 Answers 8
- Как удалить все файлы в папке Linux
- Как удалить все файлы в папке Linux
- Похожие записи
- Оцените статью
- Об авторе
- 6 комментариев к “Как удалить все файлы в папке Linux”
- How to remove all files and subdirectories in a directory WITHOUT deleting the directory in bash?
- 12 Answers 12
Unix Command to Delete all files in a directory but preserve the directory
I am looking for a unix command to delete all files within a directory without deleting the directory itself. (note the directory does not contain subdirectories).
8 Answers 8
EDIT: added -i just in case (safety first). directory should be a full or relative path (e.g. /tmp/foo or ../trash/stuffs )
of course, you can always cd to your directory and then perform a «rm -i *» please note that the -i flag will force confirmation of each deletion, is there just for safety (nasty things will occurr if you misplace a / in your commandline and you provide a -r flag. )
I’m using rm -r * but it’s asking for a confirmation on each file deletion. To stop this it’s rm -rf * yes? Trying to delete all from current directory.
-r perform recursive deletion, -f forces deletion, assuming the rm command has not been aliased, I’d go with a rm -f *
it deletes all file inside the «yourdirectory» directory
I wouldn’t suggest to a unix newbie to use the -r switch, what if OP misplaces a / on the command line ?
Understandable but the issue is that i am clearing out spam from the remote qmail folder. There is thousands of messages to clear so I need a practical way of doing it without confirmation on each deletion.
You can use find /path/to/your/folder/ -delete to delete everything within that folder.
While a wildcard rm would braek with too many files («Argument list too long»), this works no matter how many files there are.
You can also make it delete only files but preserve any subdirectories:
find /path/to/your/folder/ -type f -delete
You could also specify any other criteria find supports to restrict the «results».
Как удалить все файлы в папке Linux
Время от времени стоит чистить систему, чтобы она не засорялась ненужными данными. В случае с дистрибутивами Linux есть несколько способов удаления файлов, применимых в разных ситуациях.
Из данной статьи вы узнаете, как удалить все файлы в папке Ubuntu, в том числе скрытые и не скрытые. Заодно мы разберем важные нюансы данной процедуры, упомянув несколько способов чистки.
Как удалить все файлы в папке Linux
Многие действия в данной операционной системе удобно выполнять с помощью команд в терминале. Чистка содержимого папок тоже относится к их числу. Для начала предлагаем посмотреть полный список файлов в конкретном каталоге, на примере ~/Downloads:
find ~/Downloads -maxdepth 1 -type f
Файлы, название которых начинается с точки, являются скрытыми. Остальные – не скрытые. Простая чистка не скрытых файлов внутри директории осуществляется такой командой:
Чтобы стереть все файлы, даже скрытые, выполните эту команду:
Для просмотра всех файлов и каталогов в выбранном местоположении, в том числе и скрытых, подойдет команда find без параметров. Например:
Полная чистка директории со всеми вложенными файлами и папками (даже скрытыми) осуществляется другой командой:
Похожие записи
Оцените статью
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
Об авторе
6 комментариев к “Как удалить все файлы в папке Linux”
Спасибо за статью. А как можно настроить, что при запуске команды «rm -rf » данные не удалялись напрямую, а складывались во временную папку или в корзину, как сделано в Windows? Чтобы я потом сам удалял из корзины, после того, как убедился что ничего не поломалось после удаления. Ответить
Осознаю, не панацея. Но если устроит, то создайте такой скрипт: #!/usr/bin/bash TRASH=»/home/$USER/.trash/» if [ ! -d $TRASH ] ; then
# echo $TRASH
mkdir -p $TRASH
fi for file in $*
do
if [ -f $file ] ; then
# echo $file
mv $file $TRASH
fi
done Назовите его rm и поместите в директорий, в котором находятся Ваши личные запускаемые файлы и скрипты. У меня Debian/MATE. Такой директорий находится в домашнем директории и называется bin. Кроме того, путь к этому поддиректорию у меня задаётся в файле .bashrc. И этот путь размещён раньше пути к директорию /usr/bin/, где находится сстемная утилита rm. Таким образом при выполнении команды rm будет «срабатывать» Ваш скрип, а не системная утилита. И да! После создания скрипта не забудьте сделать его исполняемым — chmod +x. В скрипте я оставил пару команд echo. Это на тот случай, если Вам захочется с ним поиграться. Просто закомментируйте команды mkdir и mv и удалите комментарий у рядом стоящих команд echo. Ответить
Можно просто использовать gio trash: Usage:
gio trash [OPTION…] [LOCATION…] Move/Restore files or directories to the trash. Options:
-f, —force Ignore nonexistent files, never prompt
—empty Empty the trash
—list List files in the trash with their original locations
—restore Restore a file from trash to its original location (possibly recreating the directory) Note: for —restore switch, if the original location of the trashed file
already exists, it will not be overwritten unless —force is set. Ответить
Не буду даже пробовать такое. С самого начала следовало бы написать, насколько это безопасно и почему (и какие) файлы должны быть удалены из системы. Ответить
How to remove all files and subdirectories in a directory WITHOUT deleting the directory in bash?
Is there a command to remove all files and subdirectories in a directory without deleting the directory? For example if I have directory dontDeleteMe with subdirectories 1 , 2 , 3 and each subdirectory has a few pictures in it, how can I remove the subdirectories 1 , 2 , and 3 and all the files in the them, without removing the parent directory dontDeleteMe ?
12 Answers 12
To remove everything in a directory without removing the directory, type in:
Please note, the /* part is very important. If you put a space before the * , it will delete all your files in your current directory.
Also, be very careful playing with rm , -r and * all in the same command. They can be a disastrous combination.
Update: Okay, I realized if you do have hidden/dot files [filenames with dots at the beginning, e.x. .hidden ] then this will leave those files intact.
So really, the simplest solution to the original question is:
rm -rfv dontDeleteMe && mkdir dontDeleteMe
Another one would be to use find ‘s -exec option or pipe to xargs (below):
find dontDeleteMe/* -print0 | xargs -0 rm -rv
@justingrif: find dontDeleteMe/* -print0 | xargs -0 rm -rv I believe in most cases this will work, regardless of spaces, and what not. But cd to /tmp/ and make a test directory and try it out. 🙂
Re-making a directory does not equal deleting its contents. e.g. umask directory permission differences, owner differences, etc. enzotib’s answer would solve the issues with your original syntax
This is not a good answer. Using * is dangerous, and won’t work on dotfiles without «dotglob» (see below). rm -rf dontDeleteMe && mkdir dontDeleteMe doesn’t ensure that the dir is re-created with the same permissions/owner(s). Instead, use one of the find dontDeleteMe/ -mindepth 1 -delete variants below.
@NilsToedtmann, with all due respect, I did give fair warning in my answer that the * should be used with care.
Open terminal ( Ctrl + Alt + T ) ant type this:
find somedir -mindepth 1 -delete
This will match all files and directories within somedir and its (grand-)children including «hidden» dot files but excluding somedir itself because of -mindepth 1 , then -delete them.
@EricP The main difference between find with -mindepth 1 and rm is that the former will keep the directory and only delete its contents. It’s not safer per se, both will delete everything in the directory without confirmation if you have the permissions to do so. But find is more flexible (it has many more options than rm ).
The only reason rm -r ./* do not always work is because you can have hidden files and/or folder that are not matched by * .
To this end, bash provide an option to make * match everything, even hidden objects:
cd dont-delete-me shopt -s dotglob rm -r ./*
It can be useful to reset dotglob to its default (unset) state, if you keep on using the shell where you executed the above commands:
find /dontDeleteMe/ -xdev -depth -mindepth 1 -exec rm -Rf <> \;
Use xdev option to delete files only within device boundary.
To delete (in terminal) all files and subdirectories except for the base directory named «dontdelete»:
You can use find with the -delete flag:
The /* is important as it tells find to search only INSIDE the folder called «dontDeleteMe».
Also ensure that the -delete flag is at the end of the find command.
This solution doesn’t delete any hidden files, unless you enable dotglob . Otherwise, using the -mindepth 1 flag option seems the only way to get it working.
Remove all files starting with . in «directory» and all other files too.
Though as kindly noted by Neftas this solution is not safe!
This command could potentially be dangerous, since you’re also including . and .. directories. This may be avoided by changing <.*>to <. *>, but then you won’t delete hidden files with only one character, such as .a .
There is an even simpler answer:
Basic system administration lecture time: Be sure to pay attention to where you are when you use sweeping commands like this.
I can’t say that enough. I’ve had to recover a box because someone wasn’t paying attention and typed in rm -rf * while in /.
*nix assumes that if you are root or if you are sudo-ing as root that you know what you are doing. So make sure that you know what you’re doing before you do it.
An alternative which makes sure your ‘cd’ command works before you issue the ‘rm’ is to use
Actually it’s not any more or any less dangerous than what you suggest. All the && does is to chain the two commands together so that they execute at the same time. If anything my method is actually SAFER since you have to stop and .look before you execute the rm -rf *. Pausing to double check is always better.
@user30619 The && operator doesn’t just chain the commands together; it requires that each command be successful before the next one will be executed. If the cd command fails for any reason (directory doesn’t exist, privileges, etc) then the rm command won’t be executed. I’d call that safer.
I am not sure why this is so complex, help me if i am wrong
This has the slight flaw of trying to delete the current directory as well, which, of course, doesn’t work, because it’s still in use as the working directory of the invoking shell.
One can delete the current directory from inside it—and then be «in» a nonexistent directory. rmdir ../tmp , from an empty directory called tmp , will do that. The technique in this answer doesn’t delete the current directory because the rm command special-cases the specific pathnames . and .. , refusing to operate on them. Thus rm: refusing to remove ‘.’ or ‘..’ directory: skipping ‘.’ (from GNU rm, which provides /bin/rm in Ubuntu) is quite literally what is happening. rmdir . behaves similarly, though it shows a less illuminating Invalid argument error. @DavidFoerster
- Easiest thing for me — a windows expert but an ubuntu newbie
- Click the Files icon on the launcher
- Navigate to the directory where the files and folders are located that you want to delete
- Right Click in a blank area of the window next to the files and click «Open in Terminal» — leave the Files window open
- A terminal window will open and will be «set» to the folder you located
- You can type «dir» (disregard quotes when i say type) and press enter for the terminal to show a list of files and folders — just to prove you are «in» the right folder
- type «rm -rf *» and press enter
- depending on size of folders/files to delete system will pause
- When terminal prompt returns, the Files window you had opened will now say «Folder is Empty»
- I had success with this method and it gave me comfort to see the files/folder both in the Files window and as a result of the Dir command in the terminal window
- I was also comforted that the Files window displayed the folder now empty — especially since I had been chasing these files around looking for the trash folder that they were in
- Thanks to everyone else who submitted answers — it was very informative