What is $ in $'string' mean in shell scripts?

I see some examples like $'text words' or $'word\nword2' and example from your blog (How To Reverse a String In Unix / Linux Shell?) rev <<<$'42\n13' | tail -r. So I ask what the purpose of $ in $'string' when writing Bash shell scripts is?

The $‘string_here’ will activate the ANSI C standard as they are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows:

  1. \a - alert (bell)
  2. \b - backspace
  3. \E - an escape character
  4. \f - form feed
  5. \n - new line
  6. \r - carriage return
  7. \t - horizontal tab
  8. \v - vertical tab
  9. \\ - backslash
  10. \' - single quote
  11. \" - double quote
  12. \? - question mark
  13. \nnn - the eight-bit character whose value is the octal value nnn (one to three octal digits)
  14. \xHH - the eight-bit character whose value is the hexadecimal value HH (one or two hex digits)
  15. \uHHHH - the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits)
  16. \UHHHHHHHH - The Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits)
  17. \cx - a control-x character

Examples about $’string’ mean in shell scripts

Printing tab using the echo:

echo $'Foo\tBar'

Printing a new line:

echo $'Foo\nBar'

Printing Unicode:

echo $'\U0001f602'

Of course one can use the -e option

echo -e '\U0001f602'

You don’t need to use echo all time and directly pass such string to any command using $‘string’ syntax. For example:

echo -e 'Foo\tBar' | command

May be written as:

command <<<$''Foo\tBar'

Hence,

# long command
echo -e '42\n13' | rev | tac
# short version
rev <<<$'42\n13' | tac

A note about single vs double quote

You must use single quote and not double quote when you want to activate the ANSI C standard. For instance:

# correct syntax
echo $'Foo\tBar'
# wrong syntax
echo $"Foo\tBar"

However, a double-quoted string preceded by a dollar sign ($"string") will cause the string to be translated according to the current locale. If the current locale is C or POSIX, the dollar sign is ignored. If the string is translated and replaced, the replacement is double-quoted. See the following url for more info:

1 Like

Useful explanation and to the point too.

man bash is your friend.


Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki