Im having some problems to write a shell script which will give a certain type of file in the current directory.

I.e if i want to delete a certain type of extensions like .psd or jpeg, i m having some problem in logic to make a shell script. The script which i want now it should ask permission while deleting each extension like " want to delete it" if yes it should go and delete that particular file. anyone has snippet code for it.

Recommended Answers

All 6 Replies

Here you go :) Use the file extension as the only argument

#!/bin/ksh

ext=$1
for x in `ls -1d *$ext`
do
    /bin/rm -i $x
done

Hope that helps :)

Mike

that might not work well on filenames with spaces

anyway, why can't you just do something like this?

rm -i *.psd

True,

change

/bin/rm -i $x

to

/bin/rm -i "$x"

Thanks for pointing that out :)

, Mike

True,

change

/bin/rm -i $x

to

/bin/rm -i "$x"

Thanks for pointing that out :)

, Mike

no, that's not it. a for loop splits on spaces, so if you have a file of name "foo bar", your code will first assign x to "foo", and then assign it to "bar" in the next iteration, but none of these are actual filenames.

[...] a for loop splits on spaces [...]

The splitting would be caused by the unnecessary ls, if you use just globbing (for x in *"$ext" ...) that won't happen.
Of course, rm *.psd is the way to go, as long as the args size doesn't hit the ARG_MAX limit.

no, that's not it. a for loop splits on spaces, so if you have a file of name "foo bar", your code will first assign x to "foo", and then assign it to "bar" in the next iteration, but none of these are actual filenames.

I'm sorry, and I'll be the first to admit that this thread is dead; you are absolutely correct - I feel like an idiot ;)

That being said, the simple command line obviates the scripting. Thanks for pointing that out, though. Not so much for my benefit (since I pay more attention at work than in the middle of the night ;) but for everyone else who got my half-@@@ post :P

Nice catch again. I promise I will think twice before slapping any more code up here. I'm getting used to it and, in the process, apparently getting sloppy :(

Cheers,

Mike

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.