《高级Bash脚本编程指南》学习笔记(6)——基础:转义

转义

转义是一种引用单个字符的方法. 一个前面放上转义符 (\)的字符就是告诉shell这个字符按照字面的意思进行解释, 换句话说, 就是这个字符失去了它的特殊含义.

在某些特定的命令和工具中, 比如echo和sed, 转义符往往会起到相反效果 - 它反倒可能会引发出这个字符的特殊含义


特定的转义符的特殊的含义

echo和sed命令中使用

\n

表示新的一行


\r

表示回车


\t

表示水平制表符


\v

表示垂直制表符


\b

表示后退符


\a

表示"alert"(蜂鸣或者闪烁)


\0xx

转换为八进制的ASCII码, 等价于0xx


ex-转义示例:

#!/bin/bash
# escaped.sh

echo; echo
echo "\v\v\v\v"           #逐字打印
echo "========="
echo "VERTICAL TABS"
echo -e "\v\v\v\v"        #打印四个垂直制表符
echo "================="

echo "QUOTATION MARK"
echo -e "\042"            #打印引号(8进制的ASCII码中是42)
echo "============"

echo; echo "NEWLINE AND BEEP"
echo $'\n'               #新行
echo $'\a'               #警告

echo "============"
echo "QUOTATION MARK"
echo $'\t \042 \t'

echo $'\t \x22 \t'
echo "==============="

echo

quote=$'\042'           #把引号赋值到变量中
echo "$quote This is a quoted string, $quote and this lies outside th quotes."

echo

triple_underline=$'\137\137\137'
echo "triple_underline UNDERLINE $triple_underline"

echo

ABC=$'\101\102\103\010'   #ABC
echo $ABC

escape=$'\033'            #esc
echo "\"escape\" echoes as $escape"

echo; echo

exit 0

运行结果:

\v\v\v\v
=========
VERTICAL TABS





=================
QUOTATION MARK
"
============

NEWLINE AND BEEP



============
QUOTATION MARK
         " 
         " 
===============

" This is a quoted string, " and this lies outside th quotes.

triple_underline UNDERLINE ___

ABC
"escape" echoes as 

ex-转义‘\’:

echo "\"hello\",world."         # \"
echo "\$variable"               # \$
echo "\\"                       # \\

echo \z
echo \\z
echo '\z'
echo '\\z'
echo "\z"
echo "\\z"

echo "\"
运行结果:

"hello",world.
$variable
\
z
\z
\z
\\z
\z
\z
escaped.sh: line 57: unexpected EOF while looking for matching `"'

你可能感兴趣的:(Shell)