Jusi
Jusi

Reputation: 817

How to check if a specific kind of file exists in folder with shell?

Here's a simple script I use to clean up torrent downloads for my tv shows:

find . ! -path . -type d -maxdepth 3 -mindepth 3 -exec sh -c '
dir="$0"
tvnamer --batch $dir
mv $dir/*.mkv $dir/..
trash $dir
' {} ';'

How can I modify it with if statement to check if $dir has any .part files in it? I obviously only want the trash $dir part to happen when there's no .part files :)

Upvotes: 0

Views: 157

Answers (3)

devnull
devnull

Reputation: 123458

Use the test operator:

[ -f $dir/*.part ] || trash $dir

(instead of saying: trash $dir)

Saying so would execute trash $dir only if the directory contains .part files.


Alternatively, you could say:

[[ "$(ls $dir/*.part)" =~ \.part$ ]] 2>/dev/null || trash $dir

Upvotes: 1

umläute
umläute

Reputation: 31274

if you need a solution that checks whether there are one or more files matching a given pattern, you might have more luck using:

ls "${dir}"/*.part >/dev/null 2>&1 || trash "${dir}"

Upvotes: 1

pepol
pepol

Reputation: 1

You could use test(1) and && operator. For example: Change trash $dir to [ ! -e $dir/*.part ] && trash $dir which is the same as

if [ ! -e $dir/*.part ]; then
  trash $dir
fi

where [ ! -e $dir/*.part ] is calling of test(1) in following way: 'Test whether there doesn't (!) exist (-e) file ending in .part in $dir. If such file doesn't exist, this succeeds and therefore the trash part is called.

Upvotes: 0

Related Questions