Bash注釋

在本小節中,我們將瞭解如何在Bash腳本檔中插入注釋。

注釋是任何編程語言的必要組成部分。它們用於定義或說明代碼或功能的用法。注釋是有助於程式可讀性的字串。當在Bash腳本檔中執行命令時,它們不會執行。

Bash腳本提供了對兩種類型注釋的支持,就像其他編程語言一樣。

  • 單行注釋
  • 多行注釋

Bash單行注釋

要在bash中編寫單行注釋,必須在注釋的開頭使用井號(#)。以下是Bash腳本的示例,該示例在命令之間包含單行注釋:

Bash腳本

#!/bin/bash

#This is a single-line comment in Bash Script.
echo "Enter your name:"
read name
echo
#echo output, its also a single line comment
echo "The current user name is "$name""
#This is another single line comment

將上面代碼保存到一個檔:single-line-bash.sh,執行後得到以下結果:

maxsu@ubuntu:~$ chmod +x single-line-bash.sh
maxsu@ubuntu:~$ ./single-line-bash.sh
./single-line-bash.sh: line 1: i: command not found
Enter your name:
maxsu

The current user name is "maxsu"

在此可以清楚地看到,在執行命令的過程中忽略了注釋,注釋的內容並被解釋輸出。

Bash多行注釋

有兩種方法可以在bash腳本中插入多行注釋:

  • 通過在<< COMMENTCOMMENT之間加上注釋,可以在bash腳本中編寫多行注釋。
  • 也可以通過將注釋括在(:')和單引號(')之間來編寫多行注釋。

閱讀以下示例,這些示例將幫助您理解多行注釋的這兩種方式:

多行注釋-方法1

#!/bin/bash

<<BLOCK
    This is the first comment
    This is the second comment
    This is the third comment
BLOCK

echo "Hello World"

將上面代碼保存到一個檔:mulines-bash1.sh,執行後得到以下結果:

maxsu@ubuntu:~/bashcode$ vi mulines-bash1.sh
maxsu@ubuntu:~/bashcode$ ./mulines-bash1.sh
Hello World
maxsu@ubuntu:~/bashcode$

多行注釋-方法2

#!/bin/bash

: '
This is the first comment
This is the second comment
This is the third comment
'

echo "Hello World"

將上面代碼保存到一個檔:mulines-bash2.sh,執行後得到以下結果:

maxsu@ubuntu:~/bashcode$ chmod +x  mulines-bash2.sh
maxsu@ubuntu:~/bashcode$ ./mulines-bash2.sh
Hello World

在本小節中,我們討論了如何在Bash腳本檔中插入單行和多行注釋。


上一篇: 相對路徑與絕對路徑 下一篇: Bash引號