当前位置:网站首页>Shell quotation marks and escape are rarely noticed, but they are often used in writing scripts
Shell quotation marks and escape are rarely noticed, but they are often used in writing scripts
2022-06-29 11:08:00 【ghostwritten】
Shell Quotes and escapes
List of articles
Bash There is only one data type , It's just a string . No matter what data the user enters ,Bash Are treated as strings . therefore , String related quotes and escapes , Yes Bash It's very important for .
1. escape
Some characters are in Bash It has a special meaning ( such as $、&、*).
$ echo $date
$
In the example above , Output $date There will be no result , because $ It's a special character .
If you want to output these special characters as they are , You have to precede them with a backslash , Make it a normal character . This is called “ escape ”(escape).
$ echo \$date
$date
In the above command , Only in special characters $ Preceded by a backslash , Can be output as is .
The backslash itself is also a special character , If you want to output the backslash as it is , It needs to escape itself , Use two consecutive backslashes (\).
$ echo \\
\
The example above outputs the backslash itself .
Backslashes are used except to escape , It can also represent some non printable characters .
\a: Ring the bell\b: Backspace\n: Line break\r: enter\t: tabs
If you want to use these non printable characters on the command line , You can put them in quotation marks , And then use echo Ordered -e Parameters .
$ echo a\tb
atb
$ echo -e "a\tb"
a b
In the example above , The command line directly outputs non printable characters \t,Bash Cannot explain correctly . You must put them in quotation marks , And then use echo Ordered -e Parameters .
The newline character is a special character , Indicates the end of the command ,Bash After receiving this character , The input command will be interpreted and executed . Escape with a backslash in front of a newline character , This makes the newline character a normal character ,Bash It will be taken as having a length of 0 Null character processing , Thus one line of command can be written as multiple lines .
$ mv \
/path/to/foo \
/path/to/bar
# Equate to
$ mv /path/to/foo /path/to/bar
In the example above , If a command is too long , You can use a backslash at the end of a line , Rewrite it into multiple lines . This is a common way to write multiline commands .
2. Single quotation marks
Bash Allow strings to be in single or double quotation marks , To quote .
Single quotation marks are used to preserve the literal meaning of characters , All kinds of special characters are in single quotation marks , Will become normal characters , Like the asterisk (*)、 Dollar symbol ($)、 The backslash (\) etc. .
$ echo '*'
*
$ echo '$USER'
$USER
$ echo '$((2+2))'
$((2+2))
$ echo '$(echo foo)'
$(echo foo)
In the above command , Single quotation marks make Bash Expand 、 Variable references 、 Arithmetic operations and subcommands , All failed . If you do not use single quotation marks , They will all be Bash Automatic extension .
Because the backslash becomes a normal character in single quotation marks , So if it's in single quotation marks , And use single quotes , You can't use an escape , You need to put a dollar sign in front of the outer single quotation mark ($), And then the single quotation mark in the inner layer is escaped .
# Incorrect
$ echo it's # Incorrect $ echo 'it\'s' # correct $ echo $'it\'s'
however , A more reasonable way is to use single quotation marks instead of double quotation marks .
$ echo "it's"
it's
3. Double quotes
Double quotation marks are looser than single quotation marks , Most special characters are in double quotes , Will lose its special meaning , Become normal characters .
$ echo "*"
*
In the example above , wildcard * It's a special character , Put it in double quotation marks , It becomes ordinary characters , It will output as is . This needs special attention , It means , There will be no file name extension in double quotation marks .
however , Except for three special characters : Dollar symbol ($)、 The quotation marks () And the backslash (\). These three characters are in double quotation marks , Still has a special meaning , Will be Bash Automatic extension .
$ echo "$SHELL"
/bin/bash
$ echo "`date`"
Mon Jan 27 13:33:18 CST 2020
In the example above , Dollar symbol ($) And the quotation () In double quotes , Keep special meaning . The dollar sign is used to refer to variables , Backquotes are used to execute subcommands .
$ echo "I'd say: \"hello!\""
I'd say: "hello!"
$ echo "\\"
\
In the example above , The backslash holds a special meaning in the double quotation marks , Used to escape . therefore , You can use backslashes , Insert double quotation marks between double quotation marks , Or insert the backslash itself .
The newline character is in double quotation marks , It will lose its special meaning ,Bash It is no longer interpreted as the end of the command , Just as a normal newline character . So you can use double quotation marks , Enter multiline text on the command line .
$ echo "hello world"
hello
world
In the above command ,Bash Normally, the newline character will be interpreted as the end of the command , But the newline character loses its special function in double quotation marks , Just for line breaks , So you can enter multiple lines .echo The command will output the newline character as it is , When displayed, it is normally interpreted as line feed .
Another common use of double quotes is , The filename contains spaces . You have to use double quotation marks ( Or single quotation mark ), Put the file name in it .
$ ls "two words.txt"
In the above command ,two words.txt Is a file name with spaces , If you don't put it in double quotation marks , Will be Bash As two files .
Double quotation marks will keep extra spaces as they are .
$ echo "this is a test"
this is a test
Double quotes have another function , Is to save the output format of the original command .
# Single line output
$ echo $(cal)
January 2020 Japan One Two 3、 ... and Four 5、 ... and 6、 ... and 1 2 3 ... 31
# Original format output
$ echo "$(cal)"
January 2020
Japan One Two 3、 ... and Four 5、 ... and 6、 ... and
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
In the example above , If $(cal) Not in double quotation marks ,echo All the results are output in one line , Discarding all the original formats .
4. Here file
Here file (here document) Is a method of entering multiple lines of string , The format is as follows .
<< token text token
Its format is divided into start marks (<< token) And closing marks (token). The start mark is two less than signs + Here The name of the document , The name can be taken at will , Must be followed by a newline character ; The closing tag is written in a separate line at the top Here Document name , If it's not the top grid , The end tag does not work . Between the two is the content of the multiline string .
Here is a pass through Here Document output HTML Code example .
$ cat << _EOF_ <html> <head> <title> The title of your page </title> </head> <body> Your page content goes here. </body> </html> _EOF_
Here Variable substitution will occur inside the document , It also supports backslash escape , However, wildcard extensions are not supported , Double quotation marks and single quotation marks also lose their grammatical function , Into ordinary characters .
$ foo='hello world'
$ cat << _example_ $foo "$foo" '$foo' _example_
hello world
"hello world"
'hello world'
In the example above , Variable $foo A replacement has occurred , But double quotation marks and single quotation marks are output as they are , It indicates that they have lost the function of reference .
If you don't want variable substitution , You can put Here The opening tag of the document is placed in single quotation marks .
$ foo='hello world'
$ cat << '_example_' $foo "$foo" '$foo' _example_
$foo
"$foo"
'$foo'
In the example above ,Here Start tag of the document (_example_) In single quotes , Cause variable replacement to fail .
Here The essence of a document is redirection , It outputs the string redirection to a command , It is equivalent to including echo command .
$ command << token string token
# Equate to
$ echo string | command
In the above code ,Here The document is equivalent to echo Redirection of commands .
therefore ,Here Strings are only suitable for commands that can accept standard input as arguments , Not valid for other commands , such as echo Orders can't be used Here Document as a parameter .
$ echo << _example_ hello _example_
The above example will not have any output , because Here Document for echo Invalid command .
Besides ,Here The document cannot be used as the value of a variable , Parameters that can only be used for commands .
5. Here character string
Here There is also a variation of the document , be called Here character string (Here string), Use three less than signs (<<<) Express .
<<< string
Its function is to input a string through standard input , Pass to command .
Some commands take a given argument directly , And accept parameters through standard input , The result is different . That's why we have this grammar , Makes it easier to pass strings to commands through standard input , such as cat The command only accepts strings passed in by standard input .
$ cat <<< 'hi there'
# Equate to
$ echo 'hi there' | cat
The first syntax above uses Here character string , It looks semantic better than the second grammar , It's also simpler .
$ md5sum <<< 'ddd'
# Equate to
$ echo 'ddd' | md5sum
In the example above ,md5sum The command can only accept standard input as an argument , You cannot put a string directly after a command , Will be treated as a file name , namely md5sum ddd Inside ddd Will be interpreted as a file name . You can use it at this point Here character string , Pass a string to md5sum command .
Reference resources :
边栏推荐
- Ikvm Net project progress
- When the "Ai x scientific computing" is in progress, Huawei's mindspore competition question is hot, waiting for you!
- ModbusTCP协议网络学习型单路红外模块(中壳版)
- Numeric Keypad
- Online sql to htmltable tool
- Several methods of enterprise competition analysis: SWOT, Porter five forces, pest "suggestions collection"
- 那些大佬经常在bash 命令行终端不经意间666飞起的必备操作
- flink sql cdc 并行度 会不会影响顺序呀,是不是数据同步的话一般只能设置1。
- 多线程实现客户端与服务端通信(初级版本)
- (JS)数组的 pop、push、unshift、shift分别是什么?
猜你喜欢

美国EB-5移民再现利好,区域中心再授权政策被叫停

【各种**问题系列】OLTP和OLAP是啥?

BS-GX-018 基于SSM实现在校学生考试系统

历史上的今天:马斯克出生;微软推出 Office 365;蔡氏电路的发明者出生

Luoqingqi: has high-end household appliances become a red sea? Casati took the lead in breaking the game

Spark - Task 与 Partition 一一对应与参数详解

ModbusTCP协议WIFI无线学习型单路红外模块(圆壳版)

任职 22 年,PowerShell 之父将从微软离职:曾因开发 PowerShell 被微软降级过

免费送书啦!畅销书《 OpenCV图像处理入门与实践》一本全搞定

Online text filter less than specified length tool
随机推荐
如何通过WinDbg获取方法参数值
STM32F1与STM32CubeIDE编程实例-超声波测距传感器驱动
(JS)观察者模式
He was in '98. I can't play with him
那些大佬经常在bash 命令行终端不经意间666飞起的必备操作
math_数学表达式&等式方程的变形&组合操作技巧/手段积累
ModbusTCP协议网络学习型单路红外模块(双层板)
悬赏平台并没有WEB端开发,在原生开发和混合开发中哪种合适?
这个mySQL安装的时候怎么搞去了?
csdn涨薪秘籍之腾讯自动化软件测试面试题(含答案)
Recommended embedded learning books [easy to understand]
Several methods of enterprise competition analysis: SWOT, Porter five forces, pest "suggestions collection"
(JS)模仿indexOf方法寻找字符串中某个字符的位置
企业竞争分析的几种方法:SWOT、波特五力、PEST「建议收藏」
Nuc980 open source project 16- start from SPI flash (w25q128)
Xiaomi mobile phone - Unlock BL + open root permission
(JS) observer mode
Nuc980 started successfully
【NLP】文本生成专题1:基础知识
基于支持向量机的手写数字识别详解(MATLAB GUI代码,提供手写板)