我正在编写我的第一个shell脚本.在我的脚本中,我想检查是否存在某个命令,如果不存在,则安装可执行文件.我该如何检查此命令是否存在?
if #check that foobar command doesnt exist
then
#now install foobar
fi
Run Code Online (Sandbox Code Playgroud)
Iva*_*sov 229
一般来说,这取决于您的shell,但如果您使用bash,zsh,ksh或sh(由破折号提供),则以下内容应该有效:
if ! type "$foobar_command_name" > /dev/null; then
# install foobar here
fi
Run Code Online (Sandbox Code Playgroud)
对于真正的安装脚本,您可能希望确保type
在存在别名时不能成功返回foobar
.在bash中你可以这样做:
if ! foobar_loc="$(type -p "$foobar_command_name")" || [[ -z $foobar_loc ]]; then
# install foobar here
fi
Run Code Online (Sandbox Code Playgroud)
Foo*_*Bah 33
尝试使用type
:
type foobar
Run Code Online (Sandbox Code Playgroud)
例如:
$ type ls
ls is aliased to `ls --color=auto'
$ type foobar
-bash: type: foobar: not found
Run Code Online (Sandbox Code Playgroud)
which
出于以下几个原因,这是优选的:
1)默认which
实现仅支持-a
显示所有选项的选项,因此您必须找到支持别名的替代版本
2)类型将告诉你你正在看什么(无论是bash函数还是别名或适当的二进制文件).
3)类型不需要子进程
4)类型不能被二进制文件掩盖(例如,在linux框中,如果你创建一个程序调用which
它出现在真实之前的路径中which
,那么东西会击中粉丝. type
另一方面,是一个内置的shell [是的,一个下属无意中做了一次这个]
xuh*_*dev 25
有五种方式,4种用于bash,1种用于zsh:
type foobar &> /dev/null
hash foobar &> /dev/null
command -v foobar &> /dev/null
which foobar &> /dev/null
(( $+commands[foobar] ))
(仅限zsh)你可以把它们中的任何一个放到你的if
条款中.根据我的测试(https://www.topbug.net/blog/2016/10/11/speed-test-check-the-existence-of-a-command-in-bash-and-zsh/),在bash中推荐使用第一种和第三种方法,在速度方面建议在zsh中使用第五种方法.
Mor*_*ten 17
检查Bash脚本中是否存在程序非常清楚.在任何shell脚本中,command -v $command_name
如果$command_name
可以运行,最好运行测试.在bash中你可以使用hash $command_name
,也可以散列任何路径查找的结果,或者type -P $binary_name
如果你只想看二进制文件(不是函数等)
Den*_*nis 13
问题没有指定shell,因此对于使用fish的人(友好的交互式shell):
if command --search foo >/dev/null do
echo exists
else
echo does not exist
end
Run Code Online (Sandbox Code Playgroud)
对于基本的POSIX兼容性,请使用-v
标志,该标志是--search
或的别名-s
.
归档时间: |
|
查看次数: |
111722 次 |
最近记录: |