Bash 多行注释

Bash 多行注释

  • 传统的C语言多行注释
1
2
3
4
5
/*
this is a comment
this is a comment again
this is another comment
*/
  • bash多行注释

那么在bash环境中要怎么做呢?可以这样做:

1
2
3
4
5
6
#!/bin/bash
:<<\true
ls
read
`read`
true

这里涉及到两个unix知识点

  • Here Document

    Here Document 是在Linux Shell 中的一种特殊的重定向方式,它的基本的形式如下
    cmd << delimiter
    Here Document Content
    delimiter

    其作用是将两个 delimiter 之间的内容(Here Document Content 部分) 传递给cmd 作为输入参数

  • 空指令:

    :是一个unix命令,含义是do nothing

那么上面这段bash的含义是:以true作为here document的分隔符,其中所有的内容作为输出到空命令:,那么达到的效果是什么都不做,即为注释。那为什么true之前要加一个\,原因是如果不加\,那么here document内容中如果出现\或者`,那么here document转义会失败,所以需要增加\,避免转义失败。

  • 关闭注释

    上面这段bash只修改一行就可以开关注释,要怎么做?

    我们知道bash中单行注释通过#,那么如果把here document 注释了需要注释here document头尾两行。如下代码

    1
    2
    3
    4
    5
    6
    #!/bin/bash
    #:<<\true
    ls
    read
    `read`
    #true

    但是我们代码末尾的分隔符是true,所以其实不注释也没问题,执行不会有任何报错。所以只要注释here document的行首即可,代码如下

    1
    2
    3
    4
    5
    6
    #!/bin/bash
    #:<<\true
    ls
    read
    `read`
    true