Sheehan Alam
Sheehan Alam

Reputation: 60859

How can I delete contents in a folder using a bash script?

I would like to clear out my /bin folder in my project directory. How can I do this?

I tried rm -rf ~/bin but no luck

Upvotes: 11

Views: 29919

Answers (3)

dimir
dimir

Reputation: 793

~ is a shorthand to a current user home directory. So unless it's also your project directory you are doing something wrong. Other than that, clearing a directory would be

rm -rf ~/bin/*

And if you also want to clear the hidden files

rm -rf ~/bin/* ~/bin/.[a-zA-Z0-9]*

Make sure you are not doing

rm -rf ~/bin/.*

especially as root as it will also try to delete the parent directory.

UPD

Why? Since wildcard (*) is interpreted by shell as zero or more characters of any kind the .* will also match . (current directory) and .. (parent directory).

Upvotes: 21

JohnW
JohnW

Reputation: 724

rm -rf ~/bin/{*,.[^.]*}

would delete all files and directories in ~/bin/, including hidden ones (name starts with .), but not the parent directory (i.e. ..).

The .[^.]* matches all hidden files and directories whose name starts with a dot, the second char is NOT a dot, and with or without more chars.

Upvotes: 3

fge
fge

Reputation: 121692

You should say "... my bin folder", not "my /bin folder". /bin is an absolute path, bin is a relative path.

rm -rf ~/bin removes $HOME/bin, so not what you want either.

Now, it depends on where you are: if you are in your project directory when you type the command, just type rm -rf bin.

Upvotes: 13

Related Questions