Parameter expansion on a single variable works as expected. But how to expand parameters that comprise several variables? Example:


foo=/lorem/ipsum; bar=dolor/sit

printf '%s\n' "${tmp%/*}"

How to run this parameter expansion without the need of the temporary variable?

  • you introduce a '/' with the $tmp variable; it would need to be included, I assume?
    – Jeff Schaller
    Jan 16, 2016 at 20:15
  • @JeffSchaller Yes, indeed.
    – Marco
    Jan 16, 2016 at 20:31
  • What is the problem? What output are you getting and what do you expect? You should be able to use as many variables as you want within double-quotes.
    – gardenhead
    Jan 17, 2016 at 1:02

2 Answers 2


Expansion allows for only the one variable, necessitating the temp var. However, if this is the exact use case, dirname may work for you, since it does pretty much exactly the same thing as %/*:

$ foo=/lorem/ipsum; bar=dolor/sit
$ dirname $foo/$bar

Here's one ... workaround ... that does not set the temporary variable in the current shell:

foo=/lorem/ipsum; bar=dolor/sit
(tmp="$foo/$bar"; printf '%s\n' "${tmp%/*}")
  • It's contained in a shell script, so it's not a problem that the variable is there. My intention was to have a cleaner code base and reduce the number of unnecessary variables.
    – Marco
    Jan 16, 2016 at 20:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .