Linux delete file if empty

Remove files with 0 length inside bash

I want to create a bash script inside Linux terminal to go into a file and then delete it if it’s empty:

#!/bin/bash echo " Enter name of a directory" read Dir for Directory in $( ls $HOME ) do test -d $HOME/$dir if [ $# -eq 0 ] then for filename in $( ls $HOME/$Dir ) do test -d $HOME/$dir/$filename if [ ! -s "$filename" ] then rm $HOME/$dir/$filename else echo " not empty" fi done else echo " $Dir is not a directory" fi done 

This is the code I am using but it does not work. It recognizes the file created but doesn’t delete it even when empty. It Salah displays there is no such file or directory

$Dir is NOT equal to $dir FYI. Shell variables are case sensitive. UNIX is not like windows or IBM mainframes

@MelBurslan That was a manual error while writing the script here I am using the same variables but still not working

@Jay Yes exactly taking the directory as a command line argument and then checking if its empty if yes then deleting the files

Please only paste the exact code that you have tested. Having us look at the wrong code wastes our time.

2 Answers 2

Edited 2 (WildCard) + sign and raw <>

Give this a try, replace mydir in the command-line below with a directory name that needs to be worked out:

find "$"/mydir -size 0 -type f -exec rm <> + 

It is removing all empty files located in the «$»/mydir directory and its subdirectories (if any).

There is a script version below:

#!/bin/bash -- find "$"/"$" -size 0 -type f -exec rm <> + 

List all empty files under testd:

$ find "$"/testd -size 0 -type f /home/jay/testd/empty_file.txt 

Use the script to remove empty files:

$ chmod +x clearner.sh $ ./clearner.sh testd 

thx I am not at my computer so I checked on the net one online man before answering. I missed this gnu thing and the delete. I will edit the answer.

You don’t need to escape the braces. They have no special meaning to the shell when adjacent (i.e. empty). Also, +1 for sticking to POSIX. Have you considered using + instead of \; ?

thx @Wildcard I had never noticed the + sign neither the possibility to use raw <>. I used to practice on Solaris 6 — 7 — 8, maybe that is why ?

I do like using find for this since it will handle filenames with special characters well. You could do it with GNU find similar to how @Jay suggested or more portably like

find "$HOME/$dir" -type f -size 0c -exec rm <> + 

which will look in $HOME/mydir and all subdirectories. Everything that is a file ( -type f ) and has a size of 0 bytes (-size 0c) will then have its name applied as an argument to rm , and we’ll let the command line have many arguments instead of invoking rm for each file (the + instead of a \; to -exec )

Читайте также:  Linux замена графической оболочки

If you do not want to descend into subdirectories and want it to be portable you could do the following, which I’m going to put into a subshell so as not to change from the current directory in the current shell:

( cd "$HOME/$dir"; find . ! -name . -prune -type f -size 0c -exec rm <> + ) 

This will use -prune to prevent find from going into further directories, and will throw away the . directory which will prevent it from being part of the directory list that gets descended. Those two result in find only reporting results from the current directory.

Now that we’re in the current directory we can revisit the script you were writing though since we’re much closer to that approach again.

You should be careful with the approach you were trying in your script. Any file with a character in IFS (like a space or tab) would cause your for loop to be looking at partial filenames (e.g., if a file is called with space you would get with and space in different iterations). If you’re going to loop over files in a directory it is better to use globs like

for f in $HOME/$dir/*; do if [ -f "$f" ] && [ ! -s "$f" ]; then printf "It's an empty file: %s" "$f" fi done 

This glob solution will not pick up any files that start with a . though unless you enable dotglob.

Источник

Remove files of 0 bytes in size via command line?

So, I got a directory filled with other directories, and I was wondering if it was possible to remove files that have no size. Typically these files are 0 bytes and since I want to merge all these subdirs I could replace a perfectly legit file with a weightless 0 byte file, and there goes my legit file. Any way to remove the zero byte files?

4 Answers 4

Use the Find command to find files by size and print file names to standard output.

find . -type f -size 0b -print 

substitute -print with -delete to delete the files rather than print them on screen.

find . -type f -size 0b -delete 

Now, is there any way to move files from one location to another, and with the conflicts replace if the size is the same but keep both copies if the size is different?

Find and remove all files with a size of 0 recursively:

find . -type f -size 0 -print0 | xargs -I<> -0 rm <> 
% ls -og total 4 -rw-rw-r-- 1 0 Jun 7 20:31 bar -rw-rw-r-- 1 5 Jun 7 20:29 foo % find . -size 0 -print0 | xargs -I<> -0 rm <> % ls -og total 4 -rw-rw-r-- 1 5 Jun 7 20:29 foo 

You can also do it directly in the shell. This could be useful if you don’t want to delete empty hidden files (those whose name begins with a . ). While you could do that with find as well, an alternative would be to use the shell itself:

shopt -s globstar for file in **/*; do [ ! -s "$file" ] && [ -f "$file" ] && rm "$file"; done 

Explanation

  • shopt -s globstar : turns on the globstar option for bash which makes ** match one or more subdirectories. **/* will match all files and directories in the current directory and all its subdirectories.
  • for file in **/*; do . ; done : iterate over all files and directories found;
  • [ ! -s «$file» ] : [ -s «$file» ] is true if the file exists and is not empty. Therefore, [ ! -s «$file» ] (the ! inverses the test) is true if the file doesn’t exist or if it is empty.
  • [ -f «$file» ] : true if the file is a regular file. Not a directory or a device file or a symlink etc.
  • rm «$file» : delete the file.
Читайте также:  Посмотреть права папки линукс

The && ensure that the next command is only run if the previous one was successful so this will only delete empty, regular files.

Источник

Delete empty files and directories in Linux

We’ll learn how to remove empty directories and empty file on Linux.

Empty directories don’t take up any disk space, but they’re good to keep them tidy. We should clear out old files and folders periodically.

All the instructions in this tutorial are for Linux systems. They won’t work on Windows.

Delete Empty Files in a Directory

You can use the `find` command to remove all the empty files in an existing folder.

$ find . -type f -empty -print -delete

To delete empty directories, we first need to search for all the empty folders in the specified folder and then, delete them.

To find all the empty directories in the current directory, use the following command: find. −type d −empty −print | xargs rm −rf. Add the −delete option to remove them.

Let’s take an example to better explain this concept.

A directory containing both empty and non-empties may be considered. Here, the file prefixed with data-filename is a non-empty file and the one prefixed with empty is an empty file.

|-- data-file1 |-- data-file2 |-- empty-file1 |-- empty-file2 |-- empty-file3 |-- empty file 4 |-- mydir1 | |-- data-file3 | `-- empty-file5 |-- mydir2 | |-- data-file4 | `-- empty-file6 `-- mydir3 `-- mydir4 `-- mydir5

We’ll now run the above command inside these directories. It will delete all empty files recursively — meaning that the empty-file4 and empty-file5 inside the directories mydir1 and mydird2, respectively, will be removed too.

$ find . -type f -empty -print -delete ./empty-file1 ./empty-file2 ./empty-file3 ./mydir1/empty-file5 ./mydir2/empty-file6 ./empty file 4

Let’s look at the output carefully. We’ll see that this operation has removed the files whose names include spaces from the directory.

Читайте также:  Простые графические редакторы linux

It has deleted only empty files and not the directories like mydir1, mydir2, mydir4, and mydir6.

Non-Recursive Deletion of Empty Files

We’ve talked about deleting empty files from directories recursively so far. But what if we want to remove empty files from the current directory itself?

The find utility has an option −maxDepth that defines the maximum depth at which the find utility searches for files.

Using −maxdepth1, the ‘f’ (file) command will search for files in the current directory only.

$ find . -maxdepth 1 -type f -empty -print -delete ./empty-file1 ./empty-file2 ./empty-file3 ./empty file 4

Delete All Empty Directories

We can search for files by using -type f with the find command −

$ find . -type d -empty -print -delete

It will remove all the empty directories from the current directory.

Let’s run this command inside the directory where we saved our script.

$ find . -type d -empty -print -delete ./mydir3 ./mydir4/mydir5 ./mydir4

After deleting the mydir5 folder, mydir3 is no longer an empty directory; instead, it contains the files from mydir2.

Non-Recursive Deletion of Empty Directories

By using −maxdepth 1, the find utility searches only for empty directories in the current working directory.

$ find . -maxdepth 1 -type d -empty -print -delete ./mydir3

Delete Empty Files and Directories Together

It’s now finally the right moment to combine everything that we’ve learned so far. Delete all the empty files and folders from the current directory by running one command.

We’ll use the logical OR (OR) operation (-o), with the find utility, to search for empty files or directories.

$ find . -type d -empty -print -delete -o -type f -empty -print -delete ./empty-file1 ./empty-file2 ./empty-file3 ./mydir1/empty-file5 ./mydir2/empty-file6 ./mydir3 ./mydir4/mydir5 ./mydir4

The −o option splits the command from the filename into two parts. The fist part, −type d −empty − print −delete, deletes all the empty directories, whereas the second part, − type f −empty − print − delete, deletes all the files which are empty.

We can use −maxdepth 0 to delete the empty files/directoires recursively.

$ find . -maxdepth 1 -type d -empty -print -delete -o -type f -empty -print -delete ./empty-file1 ./empty-file2 ./empty-file3 ./mydir3

Conclusion

Here, we’ve learnt about empty files, empty folders, and how to remove them in Linux. We’ve looked at two different ways of deleting files − Recursive and Non−Recursive.

It is important to review all the directories and delete any unnecessary ones before removing them. In all the examples discussed above, we can use the −recurse option to review all the directories that would be removed.

As a best practice, we can set up a cron task to remove empty folders and subfolders from our system. This way, we won’t ever accumulate empty folders and subfoldes on our computer.

Источник

Оцените статью
Adblock
detector