在 Shell 脚本中,对齐代码可以使脚本更易读、维护和调试。常见的对齐方式包括使用 indent 工具、tab 或 spaces 来对齐语句。
✅ 一、使用 indent 工具对齐
indent 是一个常用的格式化工具,可以自动对齐 Shell 脚本中的代码。
安装 indent(在 Debian/Ubuntu 系统上):
sudo apt-get install indent
使用示例:
indent -i script.sh
-i:输出格式化后的脚本script.sh:要格式化的脚本文件
优点:
- 自动对齐,适合大型脚本
- 支持多种语言(包括 Shell)
✅ 二、使用 tab 或 spaces 手动对齐
如果你不想使用工具,可以手动使用 tab 或 space 来对齐。
示例脚本:
#!/bin/bash
# 这是一个示例脚本
# 它会打印一些信息并执行一些操作
echo "Hello, this is a sample script."
echo "We will print the current date and time."
date
ls -l
手动对齐方式(使用 tab):
#!/bin/bash
# This is a sample script
# It will print some information and perform some operations
echo "Hello, this is a sample script."
echo "We will print the current date and time."
date
ls -l
手动对齐方式(使用 space):
#!/bin/bash
# This is a sample script
# It will print some information and perform some operations
echo "Hello, this is a sample script."
echo "We will print the current date and time."
date
ls -l
✅ 三、使用 fmt 工具(适用于某些系统)
在某些系统中,可以使用 fmt 工具(如 fmt 在 golang 中)来格式化 Shell 脚本。
安装 fmt(在某些系统上):
sudo apt-get install fmt
使用示例:
fmt script.sh
✅ 四、使用 sed 或 awk 自定义对齐
如果你需要更复杂的对齐逻辑(例如根据行数对齐),可以使用 sed 或 awk 来处理。
✅ 五、推荐方式
- 推荐使用
indent:自动对齐,适合大型脚本 - 手动对齐:适合小型脚本,或需要精细控制对齐的场景
- 结合
fmt:如果系统支持,可以使用fmt来格式化脚本
✅ 六、示例:使用 indent 格式化脚本
# 原始脚本
#!/bin/bash
echo "Hello, this is a sample script."
echo "We will print the current date and time."
date
ls -l
# 格式化后的脚本
#!/bin/bash
echo "Hello, this is a sample script."
echo "We will print the current date and time."
date
ls -l
✅ 七、总结
| 方法 | 优点 | 缺点 |
|---|---|---|
indent |
自动对齐,适合大型脚本 | 需要安装,可能不支持所有 Shell 语法 |
tab/space |
精细控制 | 需要手动操作 |
fmt |
适合 Go 系统 | 需要安装,不适用于所有 Linux 发行版 |
如果你有具体的脚本需要对齐,可以提供代码,我可以帮你格式化。

