教你如何使用Shell显示脚本使用帮助

本文介绍了一种在Shell脚本中实现帮助信息输出的方法,通过解析脚本头部的注释,可以自动生成详细的使用说明,包括脚本功能、用法、参数选项等,方便用户理解和使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导读日常执行脚本的时候,时间久了不知道脚本的作用和实行了哪些功能,需要重新看脚本源码。因此,需要对脚本做一下输出帮助。

执行script.sh -h来显示脚本使用帮助。

格式参考:

###
### my-script — does one thing well
###
### Usage:
###   my-script <input> <output>
###
### Options:
###   <input>   Input file to read.
###   <output>  Output file to write. Use '-' for stdout.
###   -h        Show this message.

help() {
    sed -rn 's/^### ?//;T;p' "$0"
}

if [[ $# == 0 ]] || [[ "$1" == "-h" ]]; then
    help
    exit 1
fi

sed -rn 's/^### ?//;T;p' "$0"说明:

  • $0:脚本名;
  • -rn:使用扩展元字符集,屏蔽默认输出;
  • s/^### ?//:匹配### 开头的行,并删掉### 
  • T:若前面替换失败则跳转的sed脚本最后;
  • p:输出替换后的结果;

执行script.sh -h

[root@test ~]# ./aa.sh -h

my-script — does one thing well

Usage:
  my-script <input> <output>

Options:
  <input>   Input file to read.
  <output>  Output file to write. Use '-' for stdout.
  -h        Show this message.Linux就该这么学
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值