-2

I have this:

muh_dir=`cd $(dirname "$BASH_SOURCE") && pwd`

and yeah I tested the above (it has backticks) and it doesn't work well with whitespace in the pwd. On the other hand, this is better:

muh_dir="$(cd $(dirname "$BASH_SOURCE") && pwd)"

My question is - this adds 3 chars to my command the syntax changes in my editor. The first way is much nicer..is there anyway to handle whitespace with the shorter syntax or do I just bite the bullet?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

2 Answers2

2

Understand quotes, then Use More Quotes™. It really is the simplest thing you can do that will work.

As an aside, the most important property of any code is its maintainability. The number of characters is only very weakly correlated to maintainability - adding three characters to 45 (6.7% increase) to handle spaces doesn't even remotely trigger my code nose.

l0b0
  • 51,350
2

Both of your code samples will fail:

muh_dir=`cd $(dirname "$BASH_SOURCE") && pwd` muh_dir="$(cd $(dirname "$BASH_SOURCE") && pwd)"

The very minimum of quotes you must add is this:

muh_dir=`cd "$(dirname "$BASH_SOURCE")" && pwd`
            ^                         ^             Note the quotes.

However, please, please!, use $(...):

muh_dir=$(cd "$(dirname "$BASH_SOURCE")" && pwd)