Marcus Burkhart
Marcus Burkhart

Reputation: 195

Bash if file sizes are greater than 1kb

I have created a vi file and I want to check the files in my home directory to see their size. If the size of the regular file is greater than 1kb I want to back it up as a compressed file with .bak extension. I have started with the command du -h --max-depth=0 * | sort -r which list the files like...

10K archive.tar
1.0K activity48
1.0K activity47
1.0K activity46
1.0K activity45
1.0k activity44
1.0K activity43
1.0K activity42
1.0K activity41
1.0K activity40
1.0K activity39
1.0K activity38

These are some of the files listed but my thought is I need to cut field 1 and somehow create an if statement and compare the field something like if [ $x -ge 1.0 ] ; do something. Any thoughts on how I should go about the problem...?

Upvotes: 0

Views: 2296

Answers (2)

Wintermute
Wintermute

Reputation: 44023

I'd use find:

find . -maxdepth 1 -type f -size +1k -exec gzip -k -S .bak '{}' \;

I'd probably not use a custom extension for the compressed file, though; that's just asking for future confusion.

find searches a directory (. in this case) for files that pass a filter. Complex filters can be constructed; in this relatively simple case, several primitive filters are chained to select

  • Files that are no more than one level deep into . (i.e., subdirectories are not searched),
  • are regular files,
  • 1KB or larger, and
  • for which gzip -k S .bak filename exits with a status code of 0.

The -exec filter is special in that it is considered an action (other actions include -delete and -print). If a filter does not contain an action, an implicit -print action is appended to the filter so that the names of all files that fit the filter are printed. Since our filter contains an action, that does not happen.

In any case, we're not really interested in the result of the -exec filter in this case, just in its side effect of running the specified command. It is useful to know that -exec is also a filter, however, in case you want to chain commands. For example, if you wanted to copy the backup files to another folder after packing them, you could write

find . -maxdepth 1 -type f -size +1k -exec gzip -k -S .bak '{}' \; -exec cp '{}.bak' /some/where/else/ \;

Then cp filename.bak /some/where/else/ would be executed only if gzip -k -S .bak filename returned with an exit status of 0 (that is, if it indicated successful completion).

Upvotes: 3

Bjorn Munch
Bjorn Munch

Reputation: 496

find . -maxdepth 1 -type f -size +1k -exec gzip {} \;

That ought to do it. Well it produces compressed .gz files.

Upvotes: 3

Related Questions