gpt4 book ai didi

shell - 如何检查 shell 脚本中是否存在命令?

转载 作者:行者123 更新时间:2023-12-03 04:22:51 25 4
gpt4 key购买 nike

我正在编写我的第一个 shell 脚本。在我的脚本中,我想检查某个命令是否存在,如果不存在,则安装可执行文件。我如何检查这个命令是否存在?

if # Check that foobar command doesnt exist
then
# Now install foobar
fi

最佳答案

一般来说,这取决于您的 shell,但如果您使用 bash、zsh、ksh 或 sh(由 dash 提供),则以下操作应该有效:

if ! type "$foobar_command_name" > /dev/null; then
# install foobar here
fi

对于真正的安装脚本,您可能希望确保在存在别名 foobar 的情况下 type 不会成功返回。在 bash 中你可以做这样的事情:

if ! foobar_loc="$(type -p "$foobar_command_name")" || [[ -z $foobar_loc ]]; then
# install foobar here
fi

关于shell - 如何检查 shell 脚本中是否存在命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7522712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com