GitHub Actions执行bash脚本时while (( "$#" ))报错如何兼容修复?
问题解决方法
报错原因
GitHub Actions使用的Ubuntu环境中,sh指向的是POSIX标准的dash shell,而脚本中while (( "$#" ));是Bash特有的算术扩展语法,dash不支持该语法,因此触发报错。而你本地环境的sh可能是Bash的软链接,所以能正常运行脚本。
方案一:改用Bash执行脚本
这种方法最简单,直接让脚本和执行命令都使用Bash:
- 修改脚本的shebang行,将第一行从
#!/bin/sh改为#!/bin/bash - 在GitHub Actions的步骤中,用
bash命令执行脚本:
修改后的脚本开头:
#!/bin/bash REPO_NAME="my-repo" # Set defaults up top for clarity and define only once A="1" B="2" ...
修改后的GitHub Actions步骤:
- name: Run bash script run: | bash build.bash --a 3 --b 4
方案二:修改脚本兼容POSIX Shell
如果需要脚本保持POSIX兼容性(能在dash等标准sh环境运行),只需将循环条件替换为POSIX支持的写法:
将原脚本中的while (( "$#" ));改为while [ "$#" -gt 0 ];
修改后的循环部分代码:
while [ "$#" -gt 0 ]; do case "$1" in -h|--help) usage ;; --a) shift A="$1" shift ;; --b) shift B="$1" shift ;; # Unknown option *) echo "Unrecognized option: $1" usage ;; esac done
修改后无需调整GitHub Actions的执行命令,用sh build.bash --a 3 --b 4即可正常运行。
内容的提问来源于stack exchange,提问作者Jamie.Sgro
相关产品推荐
相关产品推荐

