myadeniboy
myadeniboy

Reputation: 55

Delete file with given extension

I want to remove files with extension that was given by a user. My problem is that it print "Not Found" and "rm: cannot remove ‘*.txt’"

echo Extension?
read ext

if [ -e *$ext ]
then 
    rm *$ext
else
    echo Not Found
fi

Upvotes: 1

Views: 66

Answers (2)

Pi Marillion
Pi Marillion

Reputation: 4674

Use a bash array to ensure that white space is handled correctly.

#!/bin/bash

# ask for ext until user enters one
ext=''
while [[ -z $ext ]]; do
    read -p 'Extension? ' ext
done

# find files
files=(*"$ext")
if [[ -e ${files[0]} )); then
    # delete files (-- prevents injection)
    rm -- "${files[@]}"
else
    # no files to delete
    echo "No files with extension: $ext"
fi

Upvotes: 0

Jason
Jason

Reputation: 2850

Try using the -z flag to check if the $ext variable is empty. The -e flag checks if a file exists.

#!/bin/bash
echo Extension?
read ext

if [ ! -z $ext ]
then
    rm *.$ext
else
    echo Not Found
fi

I also added a . to the rm command. This reflects the desire to remove by extension. Otherwise, you'd be removing any file that ended with the user input (i.e. program.c and a file named zodiac would both be deleted).

Upvotes: 2

Related Questions