# The following is not safe:
# var=$(dirname "$f")

# solution to this problem is very simple:
# add a safety character after the last newline,
# then use the shell's parameter substitution to remove the safety character:

var=$(
  command
  echo x
)
var=${var%?}

# in the case of the dirname command,
# one also wants to remove the single final newline added by dirname, i.e.

var=$(
  dirname "$1"
  echo x
)
var=${var%??}

# there is an easier way to get directory part of a pathname, provided you don't
# care about some of the odd corner-case semantics of the dirname command:

var=${1%/*}

# this will fail for files in root directory, among other corner cases, so a
# good approach would be to write a shell function to consider such special cases
# note, however, that such function must somehow store its results in a variable
# if it printed them to stdout, as is common practice when writing shell
# functions to process strings, we would run into the issue of `$(...)`
# stripping trailing newlines once again and be back where we started...
