Bash scripts are a great tool for us Linux admins. They primarily help us to execute commands repeatedly and/or very fast. They save much of our valuable lifetime here on earth but the bash scripting language can be very noisy, and often the resulting code is not easy to read for non-bash-gurus.

So, the bash language won’t win any beauty award, and sometimes the effect of a line bears no relation to its complexity. One great example for this is the following useful line I recently found on Stack Overflow:

It does one simple thing: it writes the path to the directory in which the bash script resides in to the variable DIR.

How to use

So, let’s assume you want to read from a file called foo.txt and this file is stored in the same directory as the bash script. Your bash script could be as follows:

If you change to the directory of the script and execute it, everything’s fine, and the file foo.txt will be printed.

But if you execute this script from any other directory it will fail, because the file foo.txt can’t be found. This is where the wonderful line from above comes into play:

Now you can execute the script from anywhere you want. The file foo.txt will be found.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">