程序员

shell脚本中$"string"和$'string'的含义

2020-09-18  本文已影响0人  洛茄
  1. 用双引号括起来的字符串前面带上$,会根据当前的locale进行翻译。

    如果当前的locale是C或者POSIX,则$会被忽略掉,可有可无。

    官方文档说明:

    3.1.2.5 Locale-Specific Translation

    A double-quoted string preceded by a dollar sign (‘$’) 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.

    Some systems use the message catalog selected by the LC_MESSAGES shell variable. Others create the name of the message catalog from the value of the TEXTDOMAIN shell variable, possibly adding a suffix of ‘.mo’. If you use the TEXTDOMAIN variable, you may need to set the TEXTDOMAINDIR variable to the location of the message catalog files. Still others use both variables in this fashion: TEXTDOMAINDIR/LC_MESSAGES/LC_MESSAGES/TEXTDOMAIN.mo.

  2. 用单引号括起来的字符串前面带上$,我们称之为ANSI-C Quoting;

    不带$的单引号字符串,我们称之为single-quoted。

    对于ANSI-C Quoting,字符串里用反斜杠转义的字符会被替换成由ANSI C标准指定的实际输出和动作。

    比如下面的示例,单引号的字符串前带上$,可以将\n转义成newline,使其另起一行。

    [root@localhost /]# echo -n $"test\n"
    test\n[root@localhost /]# echo -n $'test\n'
    test
    [root@localhost /]# echo -n "test\n" 
    test\n[root@localhost /]#
    

    官方文档说明:

    3.1.2.4 ANSI-C Quoting

    Words of the form $'string' 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:

参考资料:
https://www.gnu.org/software/bash/manual/html_node/Locale-Translation.html
https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html

上一篇下一篇

猜你喜欢

热点阅读