Bash字符串处理(与Java对照) - 2.字符串的表示方式(字符串常量)(三)

2014-11-24 02:40:31 · 作者: · 浏览: 6
. Within a script, though, this problem does not occur, since the Bash history mechanism is disabled then.

在命令行环境,感叹号(!)称之为“历史扩展字符(the history expansion character)”。
[root@jfht ~]# pwd
/root
[root@jfht ~]# echo "!"
-bash: !: event not found
[root@jfht ~]# echo "!pwd"
echo "pwd"
pwd
[root@jfht ~]#

在脚本中使用感叹号,将不会进行历史扩展。

Bash脚本:test_exclamation_mark.sh
Bash代码
#!/bin/sh

echo "!"

pwd
echo "!pwd"

[root@smsgw root]# ./test_exclamation_mark.sh
!
/root
!pwd
[root@smsgw root]#


$' ... '(ANSI-C Quoting)
前面讲到,包围在单引号之内的字符都不会有特殊含义,所以单引号本身并不能在一对单引号中出现。但是在前面加上$之后,就可以使用\进行转义了,\的转义含义与C语言中的相同。
Advanced Bash-Scripting Guide: Chapter 3. Special Characters 写道
$' ... '
Quoted string expansion. This construct expands single or multiple escaped octal or hex values into ASCII or Unicode characters.

Advanced Bash-Scripting Guide: 5.2. Escaping 写道
The $' ... ' quoted string-expansion construct is a mechanism that uses escaped octal or hex values to assign ASCII characters to variables, e.g., quote=$'\042'.

man bash 写道
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped charac-
ters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as fol-
lows:
\a alert (bell)
\b backspace
\e an escape character (not ANSI C)
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\' single quote
\nnn the eight-bit character whose value is the octal value nnn (one to three digits)
\xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits)
\cx a control-x character

The expanded result is single-quoted, as if the dollar sign had not been present.

叮当一声。
[root@jfht ~]# echo $'\a'

叮当三声。
[root@jfht ~]# echo $'\a\a\a'

单引号。
[root@jfht ~]# echo $'\''
'
八进制表示的ASCII字符。
[root@jfht ~]# echo $'\101\102\103\010'
ABC
[root@jfht ~]#
[root@jfht ~]#

$"..."(Locale-Specific Translation)
在双引号之前加上$,这部分内容还未能很好的理解,就不说了。望高人指点一二。
man bash 写道
A double-quoted string preceded by a dollar sign ($) will cause the
string to be translated according to the current locale. If the cur-
rent locale is C or POSIX, the dollar sign is ignored. If the string
is translated and replaced, the replacement is double-quoted.

作者“Bash @ Linux