Thursday, April 14, 2022

[SOLVED] In shell, how to remove file if bigger than 100MB, move otherwise

Issue

What would be the easiest way to do the following with shell commands?

Pseudo code: rm abc if >100MB else mv abc /tmp

abc could either be a name of ONE file or ONE directory.

I want to have an alias that if run on a file or directory, it removes it if it's size is greater than 100MB and if not, it moves it to another directory. I know I could accomplish something similar with a whole fuction, but there must be a slick one-liner that could do the same.


Solution

To move a single regular file if its size is lower than 100MB and delete it otherwise, you can use the following commands :

# 104857600 = 1024 * 1024 * 100 = 100M
[ $(stat --printf '%s' "$file") -gt 104857600 ] && rm "$file" || mv "$file" /tmp/

To move a single directory and its content if its combined size is lower than 100MB and delete it otherwise, you can use the following commands :

[ $(du -s "$directory" | cut -f1) -gt 104857600  ] && rm -rf "$directory" || mv "$directory" /tmp/

To do one or the other depending on whether the input parameter points to a file or a directory, you can use if [ -d "$path" ]; then <directory pipeline>; else <file pipeline>; fi.

To recursively move or delete all the files of a directory depending on their size you can use the following :

find . -type f -a \( -size +100M -exec rm {} + -o -exec mv -t /tmp/ {} + \)

It first selects files in the current directory, then execute rm ... with the list of those files whose size is greater than 100M and mv ... /tmp with the rest of the files.



Answered By - Aaron
Answer Checked By - Terry (WPSolving Volunteer)