Skip to content
Advertisement

Inconsistent behavior when replacing substring with tilde “~” in a BASH parameter expansion

I came across some strangely inconsistent behavior in BASH parameter expansions across a few different servers, while trying to write a quick function.

On some versions of BASH, to use a tilde in a substring replacement, the tilde must be escaped, or it will be re-expanded to the home directory:

JavaScript

while on other systems, it will not be re-expanded, and attempting to escape the tilde will add the literal escape characters to the string:

JavaScript

Note my goal here is to insert the literal string “~”.


The BASH versions where no escape was necessary are here:

JavaScript

The BASH version where an escape was necessary is here:

JavaScript

So what is going on?

Advertisement

Answer

@iBug posted how to ensure we always expand the tilde. To ensure we always get the tilde character itself on any system, use this:

JavaScript

which redoes the substitution with escaped tilde only if the original non-escaped tilde was expanded.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement