如何在 Shell 脚本中添加注释 ?
在使用 shell 脚本时,添加注释让脚本更容易理解、维护和调试。理解如何在 shell 脚本中添加注释是 shell 脚本编写的一项基本技能。
单行注释
shell 脚本中最常用的注释形式是 单行注释
基本语法:
# This is a single-line comment
echo "Hello Techies" # This is an inline comment
示例如下:
多行注释
与某些编程语言不同,shell 脚本没有内置的多行注释语法。但是,使用以下方法可以达到相同效果。
1: 使用多个#符号
#!/bin/bash
# This script shows a welcome message
# It also displays the current date and time
# and the logged-in username
2: 使用 Heredocs
$ vi multiline-comments.sh
#!/bin/bash
<<COMMENT
This is a heredoc comment.
It can also span multiple lines.
This text will not be executed.
echo “Welcome to Comments Section”
COMMENT
name=$(hostname)
echo "HOSTNAME=$name"
if [ $? -eq 0 ]; then
echo "Welcome to Shell Script World"
else
echo "Something is wrong, please correct it"
fi
带注释的 Shell 脚本示例
下面是一个简单的 bash 脚本注释示例,包含两种类型的注释。
$ vi comments-script.sh
#!/bin/bash
# This script greets the user and shows the current date and time
<<COMMENT
Author: Your Name
Date: 2025-04-12
Description:
This shell script prints a welcome message,
greets the user, and displays the current date.
COMMENT
# Get the current username
user=$(whoami)
# Display welcome message
echo "Hello, $user!"
# Display current date and time
echo "Current date and time: $(date)"
我的开源项目
评论已关闭