Shell – What Does `[$’\r\n’]` Mean?

escape-charactersshell

I regularly use the expression line=${line//[$'\r\n']}. But what does [$'\r\n'] mean?

I know it removes the '\r\n' characters but how does it do this? Does it remove the instances of both characters only, or does it also find matches of just one character?

I do not understand the usage of this syntax.

If you can, please, give me a link to the manual. I cannot find the answer on this question.

Best Answer

From the Bash manual:

${parameter/pattern/string}
The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. The match is performed according to the rules described below (see Pattern Matching). If pattern begins with /, all matches of pattern are replaced with string. ... If string is null, matches of pattern are deleted and the / following pattern may be omitted.

You have ${line//[$'\r\n']}, where:

  • the parameter is line,
  • the pattern is /[$'\r\n'] (note: begins with /, so all matches of pattern are replaced), and
  • the string is null, so the / after pattern is omitted, and matches are deleted.

Following the rules for Pattern Matching:

[…]
Matches any one of the enclosed characters.

$'...' tells bash to interpret certain escape sequences (here, \r for carriage return and \n for line feed) and replace them with actual characters represented by the escape sequences.

So this substitution matches all instances of either carriage return (CR, \r) or line feed (LF, \n), and deletes them.