bash shell 脚本中的“结束”命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27799999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:08:00  来源:igfitidea点击:

'End' command in shell script

bashshellunixheredoc

提问by Santhiya

I am trying to understand part of a shell script that appears to be very confusing for me.

我试图理解对我来说似乎很困惑的部分 shell 脚本。

This is the snippet. My questions are:

这是片段。我的问题是:

a) what does <<-do? Is it like a standard expression . I am only aware of >, >>and <for redirection.

a) 有什么作用<<-?是不是像一个标准的表达。我只知道>,>><重定向。

b) What could Endmean? I am assuming that all the values from 'n' till 'somefilename.dat.summary' is some sort of input that is send to the script 'collapse4' and it's output is redirected to /dev/null which i learned is a place where we send unwanted data.

b) 可能End意味着什么?我假设从 'n' 到 'somefilename.dat.summary' 的所有值都是某种输入,发送到脚本 'collapse4' 并且它的输出被重定向到 /dev/null 我了解到是一个地方我们发送不需要的数据。

/usr/can/bin/collapse4<<-End > /dev/null
n
n
1
9 14
y
1
26
8
30
8
1
23
3
1
n
n
y
n
n
somefilename.dat
somefilename.dat.summary
End

回答by fedorqui 'SO stop harming'

This command sends a block of text to /usr/can/bin/collapse4and redirects the output to /dev/null.

此命令将文本块发送到/usr/can/bin/collapse4并将输出重定向到/dev/null.

This structure is called here doc. Endis the way you "call" the text you are about to insert. Once you are done, you indicate the end of the block with the same word in the very beginning of a new line.

这种结构在此处称为 doc。End是您“调用”要插入的文本的方式。完成后,在新行的最开始用相同的单词指示块的结尾。

But you can call it whatever. This would do the same:

但是你可以随便叫它。这会做同样的事情:

/usr/can/bin/collapse4<<-HelloJustTesting > /dev/null
n
n
1
...
n
somefilename.dat
somefilename.dat.summary
HelloJustTesting

More information in How can I write a here doc to a file in Bash script?:

如何将此处的文档写入 Bash 脚本中的文件中的更多信息

In a shell script, you may want to use indentation to make the code readable, however this can have the undesirable effect of indenting the text within your here document. In this case, use use <<-(followed by a dash) to disable leading tabs (Notethat to test this you will need to replace the leading whitespace with a tab character, since I cannot print actual tab characters here.)

在 shell 脚本中,您可能希望使用缩进来使代码可读,但是这可能会产生在此处文档中缩进文本的不良影响。在这种情况下,使用 use <<-(后跟一个破折号)来禁用前导制表符(请注意,要测试这一点,您需要用制表符替换前导空格,因为我无法在此处打印实际的制表符。)