我想检查系统上是否安装了nodejs。 我收到以下错误:
错误:未找到命令。
该如何解决?
#!/bin/bash
if [ nodejs -v ]; then
echo "nodejs found"
else
echo "nodejs not found"
fi
command
。if command -v nodejs >/dev/null 2>&1 ; then
echo "nodejs found"
echo "version: $(nodejs -v)"
else
echo "nodejs not found"
fi
#!/bin/bash
echo -n "Checking dependencies... "
for name in youtube-dl yad ffmpeg
do
[[ $(which $name 2>/dev/null) ]] || { echo -en "\n$name needs to be installed. Use 'sudo apt-get install $name'";deps=1; }
done
[[ $deps -ne 1 ]] && echo "OK" || { echo -en "\nInstall the above and rerun this script\n";exit 1; }
which
。 - Leonhardt Willewhich
的确切原因的人(比如我自己),这里有更多信息:https://dev59.com/2nRB5IYBdhLWcg3wiHv7 - Alex Wnode
,而不是nodejs
。如果存在,则返回该命令的路径到标准输出(stdout)。if [ $(which node 2>/dev/null) ]; then
echo "nodejs found"
else
echo "nodejs not found"
fi
which
。 - Leonhardt Willewhich
的确切原因的人(比如我自己),这里有更多信息:https://dev59.com/2nRB5IYBdhLWcg3wiHv7 - Alex W您可以通过以下方式检查程序或函数是否存在:
type nodejs &>/dev/null || echo "node js not installed"
如何修复它?
if node -v &>/dev/null; then
echo "nodejs found"
else
echo "nodejs not found"
fi
kind
和kubectl
)。for app in kind kubectl; do command -v "${app}" &>/dev/null || not_available+=("${app}"); done
(( ${#not_available[@]} > 0 )) && echo "Please install missing dependencies: ${not_available[*]}" 1>&2 && exit 1
或者更不简洁地表达:
unset not_available # script safety, however not necessary.
for app in kind kubectl; do
if ! command -v "${app}" &>/dev/null; then
not_available+=("${app}")
fi
done
if (( ${#not_available[@]} > 0 )); then
echo "Please install missing dependencies: ${not_available[@]}" 1>&2
exit 1
fi
然后我想要一种不需要循环就能做到同样效果的方法,于是想出了这个:
not_installed=$(command -V kind kubectl 2>&1 | awk -F': +' '$NF == "not found" {printf "%s ", $(NF-1)}')
[[ -n ${not_installed} ]] && echo "Please install missing dependencies: ${not_installed}" 1>&2 && exit 1
command -V
可以接受任意数量的条目,并将结果返回到 stdout 和 stderr(尽管我将两者都重定向到 stdout 以供下一个命令解析)。
awk
将字段分隔符设置为 <冒号><一个或多个空格>
,表示为 : +
。如果最后一个字段包含 "not found",则打印倒数第二个字段,即未安装的命令的名称。
最后,如果变量包含任何数据,则报告缺少哪些依赖项到 stderr
并 exit
脚本!
你可以以无数种方式进行依赖性检查,但这里有几个更通用且不太冗长,同时易于遵循的替代方案。 :]
if [ "$(which openssl)" = "" ] ;then
echo "This script requires openssl, please resolve and try again."
exit 1
fi
which
。 - Leonhardt Willewhich
的确切原因的人,这里有更多的信息:https://dev59.com/2nRB5IYBdhLWcg3wiHv7 - Alex W
help command
以获取正确的文档,因为它是一个shell内置命令。顺便说一句,现在我可能会建议使用type
内置命令,因为它有更多选项来包含/排除函数和别名。 - hek2mglhelp
,但我的 shell 找不到它。刚才我意识到我实际上一直在尝试在 zsh 中使用它。感谢澄清。我一直在使用type
内置命令,但现在切换到了command
,因为这是这里最受欢迎的(没有明确的最佳实践)。我想我会切换回type
。如果您能在答案中更新关于type
的评论,那还好吗?或者这并不是很重要? - Fanatiquecommand
是这里正确的工具,因为它不包括shell函数。(type -f
也可以工作,但它更加复杂) - hek2mgl