Ene*_*han 189 shell comments multiline
我最近开始研究shell脚本,我希望能够在shell脚本中注释掉一组行.我的意思是在C/Java的情况下:
/* comment1
comment2
comment3
*/`
Run Code Online (Sandbox Code Playgroud)
我怎么能这样做?
Veg*_*gas 335
使用: '打开和'关闭.
例如:
: '
This is a
very neat comment
in bash
'
Run Code Online (Sandbox Code Playgroud)
Dav*_*wii 115
bash中的多行注释
: <<'END_COMMENT'
This is a heredoc (<<) redirected to a NOP command (:).
The single quotes around END_COMMENT are important,
because it disables variable resolving and command resolving
within these lines. Without the single-quotes around END_COMMENT,
the following two $() `` commands would get executed:
$(gibberish command)
`rm -fr mydir`
comment1
comment2
comment3
END_COMMENT
Run Code Online (Sandbox Code Playgroud)
Oli*_*ver 31
Bash不提供内置功能,但有使用现有bash语法的黑客攻击.最简单的是使用HEREDOC,但要明确你正在做什么,并在任何地方使用相同的HEREDOC标记:
<< --MULTILINE-COMMENT--
line 1
line 2
line 3
line 4
--MULTILINE-COMMENT--
Run Code Online (Sandbox Code Playgroud)
一些帖子提到必须引用HEREDOC标记以避免一些shell解析副作用.如果您在评论中使用反引号,我只发现这是必要的.即使set -o verbose和$variables注释中,引用标记是没有必要的.因人而异.
如果您使用: '另一个答案中提到的方法,然后通过元评论记录它是什么,在任何地方使用相同的元评论,并记住'将评论中的任何出现加倍(语法着色编辑器将使其显而易见):
: 'Multiline comment:
line 1
line 2 we''re going to try this eventually
line 3
'
Run Code Online (Sandbox Code Playgroud)
两者都是黑客,所以他们将来可以打破脚本.
肯定有其他技术,但似乎没有"传统"的方法来做到这一点.
noa*_*mtm 20
在阅读了其他答案之后,我想出了下面的内容,恕我直言,这显然是一个评论.特别适合脚本使用信息:
<< ////
Usage:
This script launches a spaceship to the moon. It's doing so by
leveraging the power of the Fifth Element, AKA Leeloo.
Will only work if you're Bruce Willis or a relative of Milla Jovovich.
////
Run Code Online (Sandbox Code Playgroud)
作为程序员,斜线序列会立即在我的大脑中注册为注释(即使斜线通常用于行注释).
当然,"////"只是一个字符串; 前缀和后缀中的斜杠数必须相等.
你对这个有什么看法?
function giveitauniquename()
{
so this is a comment
echo "there's no need to further escape apostrophes/etc if you are commenting your code this way"
the drawback is it will be stored in memory as a function as long as your script runs unless you explicitly unset it
only valid-ish bash allowed inside for instance these would not work without the "pound" signs:
1, for #((
2, this #wouldn't work either
function giveitadifferentuniquename()
{
echo nestable
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了选择的答案,但发现当我运行一个包含它的 shell 脚本时,整个事情都被打印到屏幕上(类似于 jupyter notebooks 如何打印出'''xx'''引号中的所有内容)并且最后有一条错误消息。它什么也没做,但是:可怕。然后我在编辑它时意识到单引号可以跨越多行。所以..让我们将块分配给一个变量。
x='
echo "these lines will all become comments."
echo "just make sure you don_t use single-quotes!"
ls -l
date
'
Run Code Online (Sandbox Code Playgroud)