Home > Bash, Tip > Watch out these bash wildcards

Watch out these bash wildcards

I would like to list a couple of mistakes I used to make often when using Linux commands:

1. Remove contents of a folder with rm
Let’s say I have a folder ~/data/docs and I want to empty it. There are hidden files (files that start with . ) along with files with regular names.
The wrong way:

$ rm -rf ~/data/docs/*

the above command will remove all files and directories under ~/data/docs except the hidden ones.

The right way:

$ rm -rf ~/data/docs/* ~/data/docs/.* 2>/dev/null


$ rm -rf ~/data/docs/{*,.*} 2>/dev/null

Note: the trailing 2>/dev/null suppresses the following error messages

rm: cannot remove `.' directory `/home/rico/data/docs/.'
rm: cannot remove `..' directory `/home/rico/data/docs/..'

An even better way

$ cd ~/data/docs
$ find . -delete

Note: using only the find command

find ~/data/docs -delete

will delete the folder ~/data/docs as well, hence the cd command.


2. Rsync contents of folder src with dest
The wrong way: (unless copying only non-hidden items is the goal)

$ rsync -av /path/to/src/* /path/to/dest/

Similar to the rm mistake. Using rsync this way will only copy non-hidden files and folders from src/ to dest/

The right way:

$ rsync -av /path/to/src/ /path/to/dest/

Be careful not to type this instead [ without the trailing slash after src ]:

$ rsync -av /path/to/src /path/to/dest/

as that will put folder src instead of the content of it under /path/to/dest, that is, after running the above command, the destination folder structure will have the following folder:

Categories: Bash, Tip
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: