考虑以下 bash 脚本:
#!/bin/bash
# List of required commands
required_commands=('git', 'curl', 'sdfsdf', 'jq')
# this will correctly exit if the 'git' command is missing
cc1='git'
command -v '$cc1' >/dev/null 2>&1 || { echo "Missing '$cc1' cannot run."; exit 1; }
# this function, when called below will have an error exit code for each
missing_commands=()
check_command() {
command -v "$1" >/dev/null 2>&1 || missing_commands+=("$1")
}
# check each required command
for cmd in "${required_commands[@]}"; do
check_command "$cmd"
done
# Check if any commands are missing
if [ ${#missing_commands[@]} -eq 0 ]; then
echo "All required commands are available. Starting the script..."
# Your script continues here
else
echo "The following commands are required but not installed:"
for missing_cmd in "${missing_commands[@]}"; do
echo " - $missing_cmd"
done
exit 1
fi
# continue if all commands are available
echo "All required commands are available. Starting."
不幸的是,当在
check_command()
函数内部调用时,command -v "$1" >/dev/null 2>&1
的退出代码始终非零?这看起来很不寻常,我不明白有什么区别。
这里的目标操作系统是 MacOS Sonoma 14.2.1 (23C71),在普通终端中的 ZSH 中运行。
感谢 @Cyrus 和 https://shellcheck.net 的帮助,答案原来是我自己的愚蠢......逗号不用作 bash 数组中的分隔符,所以下面的行:
required_commands=('git', 'curl', 'sdfsdf', 'jq')
结果有四个项目,每个项目都以
,
字符结尾。哎呀。