Here Document Usage
Here Document it can be understood as "embedded documents" "embedded documents" "Now documents", which data or commands to be processed and the code string together , the amount of data suitable for a command to be processed is small, unnecessarily in which case a separate file.
Generally speaking, when embedding multiple rows of data in a short script, Here Document is useful, but embedding a lot of data, or should keep your logic (your code) and your input (your data ) separation, preferably in different files.
usage | Explanation | |
---|---|---|
command <<END document END |
|
|
demand | script | result |
cat command typically read from the file and the contents output to the display, With Here Document, cat command can read from the keyboard |
cat <<TEST > test1 > Test > Spaces before TEST # terminator, do not take effect > TEST # top grid write a terminator, not output |
test1 Test TEST
Marks the end of the body can also occur And not the top grid to write, I will not take effect. |
Here Document use in a script file, content and document conversion in uppercase. |
|
ONE TWO THREE ABCDEFGH tr command to convert said capital letters lowercase letters |
Command substitution And then to the command by default, document appear in variable or command will be evaluated or run, Shell will first replace them later They may be surrounded delimiter single or double quotes makes replacing failed Shell |
1. By default
2. single / double quotes the command to replace a failed END 1) single quotes
2) double quotes
|
Output: qpy is a girl 输出:${name} is a girl 输出:${name} is a girl |
Here Document when used in a script file, if the line in the document's first use of tabs, By default, the first row of tabs is also treated as part of the body, but can also in
Tabs are mainly used for code alignment |
1. By default #!/bin/bash cat <<END aaa bbb ccc END 2. #!/bin/bash cat <<-END aaa bbb ccc END |
Export
Export
|
Here Document most commonly used functions or display usage information to a user command or script |
|
Here String Usage
Here String is a variant of the Here Document
usage | Explanation | |
---|---|---|
command <<< string |
|
|
需求 | 脚本 | 结果 |
将小写字符串转换为大写字符串 | tr a-z A-Z <<< one |
ONE |
使用双引号,会解析字符串中的变量 | tr a-z A-Z <<< "one two three" var=two tr a-z A-Z <<<"one $var there" |
ONE TWO THREE ONE TWO THREE |
使用单引号,不会解析变量 | var=two tr a-z A-Z <<<'one $var there' |
ONE $VAR THERE |
使用引号,Here String 可以接收多行字符串作为命令的输入 | tr a-z A-Z <<<"one two there > four five six > seven eight" |
ONE TWO THERE FOUR FIVE SIX SEVEN EIGHT |