A Shell Tricks: Dash-Minus Fuss

A Shell Tricks: Dash-Minus Fuss
Photo by Giulia May / Unsplash

My friend Ahmed has recently posted a few Linux and Shell keepsakes. So today, I followed his lead and started publishing a few of mine's.  

To state the obvious. The commands below were tested on Red Hat Linux systems with Bash v4.x. If you manage to find KSH or CSH nowadays, you have my respect.

All *nix systems are similar to ogres and onions - all have layers. System layer, user layer, core commands with the neanderthal accessory lines, modern commands, and all kinds of scripts. It adds to neverending fun because command-line warriors should memorize all kid of argument notations and formats for a score of the most common tools.

Let's take a look at the command below:

tar zcf --exclude tmp/* /some/remote/volume/backup.tgz my_data_folder/
The Booby Trap command

At first glance, the command looks legit, except it does not. You may expect a new backup on some network device, but you create an archive '--exclude' on your local filesystem. It happens because the Linux kernel allows almost any character in the file and folder names, but not all commands concur. The fun begins when you try to delete this file. None of the commands below would work because rm interprets it as an argument and fails to parse it.

rm --exclude
rm \--exclude
rm "--exclude"
rm '--exclude'
That is not going to happen. Therefore, command treats - as an argument start character.

Fortunately, it has a straightforward fix. The latest BASH version gives you a tip - don't use a relative path; use the absolute one. Then, in the version below, you can delete it and run the well-formatted tar command.

rm ./--exclude
tar zcf --exclude=tmp/* /some/remote/volume/backup.tg my_data_folder/
In case you haven't noticed, now exclude option includes = sign.

There are a few more situations where '-' could give you grief. My second best one is search content similar to -something.  

To be continued ...