Linux tips and tricks

I’ll expand this page gradually, so keep checking back for new tips/tricks.

The && bash operator.  Invaluable.

Put your hands up, bash people, who doesn’t know the difference between & and && in bash?  It’s surprisingly simple.  The single & operator means “do this AND this”, whereas the double && operator means “do this, if it returns true then also do this”.  The opposite is true of the || operator, which says “do this and if it fails do this other thing”.

The most overwhelmingly simple example of &&’s infinite versatility is the following cron script which I use to update my system nightly:

apt-get update &&
apt-get upgrade -fy

This can also be used to obsolete some complicated if/then/else statements by replacing them with && and || operators:

if [ -d /home/c/myDir ]; then
  echo "Yes, myDir is a directory!";

One can replace the above with:

[ -d /home/c/myDir] && echo "Yes, myDir is a directory!";

Which may seem a bit odd in this particular example, but in many cases the resultant script becomes easier to read and manage.


Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s