linuxbashshell的getopt以及函数用法小记
- 软件开发
- 2025-08-05 12:06:02

getopt 长选项 短选项 可选参数whilecaseifbasename函数变量shiftread
实现功能描述:
1. 实现可选参数传入 -c 或 --clearBuild。
2. 用shell脚本来实现选择,make时是否clean。
3. 可以打印用法帮助 和 作者信息。
#!/bin/bash # sh函数定义 *************************** usage() { sh_name=$(basename $1); # sh_name='basename $1'; #或者这个 echo " --------------- 用法: $sh_name [选项] <(可选) -c > <(可选) --clearBuild > 命令行选项: -c 或 --clearBuild 默认: 0, 表示是否清除make build的内容,数值为1表示清理,为0表示直接构建 可选选项: -h 或 --help 打印帮助信息 -a 或 --author 打印作者信息 --------------- " exit 1; } author() { sh_name=$(basename $1); # sh_name='basename $1'; #或者这个 echo " --------------- 脚本: $sh_name 作者: WJH --------------- " exit 1; } fun1_make() { if [ "$1" = "clear" ] ; then # echo '执行清理并构建文件'; echo 'in fun1_make(): 先clean 然后 make'; # your cmd ..... else # echo "不清除已经构建好的文件" echo "in fun1_make(): 直接make" # your cmd ..... fi } # sh变量定义与接收 *************************** # 输入指令 parameters=$(getopt -a -o c::ha -l clearBuild::,help,author -n "$0" -- "$@") # echo "原始参数origin param is $@" if [ $? != 0 ]; then echo "脚本解析失败..."; exit 1; fi # set命令将规范化后的命令参数分配到位置参数 $1 $2上面 eval set -- "${parameters}" # echo "规范后参数formatetd parameters=[$@]" # sh识别输入的选项·参数 *************************** while true; do case "$1" in -c | --clearBuild) case "$2" in "") echo "选项 --clearBuild 无参数"; clearBuild=${clearBuild:=1}; #赋默认值 shift 2; # 可选参数仍有空参数,需要shift 2, ;; *) echo "选项 --clearBuild 参数为:$2"; clearBuild=$2; shift 2; ;; esac ;; -h|--help) usage $0 ; ;; -a|--author) author $0 ; ;; --) echo "clearBuild 默认值 1, clearBuild 现在数值:$clearBuild"; # 默认值见 68行 echo "-----------------"; shift 1; break; ;; *) echo "Internal error!!!"; exit 1 ; ;; esac done # sh业务逻辑 *************************** # 比较字符串是否相等用 =, 并在两边留空格 # 比较数字用 -eq -gt -lt 等,分别为 equal; greater than; less than;等 if [ "$clearBuild" = "1" ] ; then # 输入了 选项时 或 可选参数时 echo '>>>执行清理,然后构建'; fun1_make clear; # your cmd ..... elif [ "$clearBuild" = "0" ] ; then # 输入了 选项时 或 可选参数时 echo ">>>直接构建" fun1_make direct_build; # your cmd ..... else # 未输入 选项时 read -p '未输入 选项时: 输入clear 确认清除并重新构建; 输入不为clear,直接构建 : ' tmp2 if [ "$tmp2" = "clear" ] ; then echo ">>>执行清理,然后构建"; fun1_make $tmp2; # your cmd ..... else echo ">>>直接构建" fun1_make $tmp2; # your cmd ..... fi fi echo "-----------------";参考文章
1.设计shell脚本选项:getopt - 骏马金龙 - 博客园 (cnblogs.com)
2.081_扩展篇_Shell编程(七)_函数(二)_自定义函数_哔哩哔哩_bilibili
3.Linux——shell脚本的传参方式 - moutory - 博客园 (cnblogs.com)
linuxbashshell的getopt以及函数用法小记由讯客互联软件开发栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“linuxbashshell的getopt以及函数用法小记”