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

And*_*rew 148 shell

我正在编写我的第一个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">/dev/null 2>&1;` (8认同)
  • `>/dev/null 2>&1`与`&>/dev/null`相同 (7认同)
  • 嗯...当我把它改成`if!输入“ foo”> / dev / null;`,然后在屏幕上显示输出“ myscript.sh:第12行:type:foo:not found”,但是,它仍然可以正常工作,因为当我说`if!输入“ ls”> / dev / null;`没有输出,并且if语句也不会执行(因为它返回true)。当命令不存在时,如何使输出静音? (3认同)

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 [是的,一个下属无意中做了一次这个]

  • 你能把它以if/else语句的形式(不输出到控制台)吗? (4认同)

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.ne​​t/blog/2016/10/11/speed-test-check-the-existence-of-a-command-in-bash-and-zsh/),在bash中推荐使用第一种和第三种方法,在速度方面建议在zsh中使用第五种方法.

  • @Raptor `if` 检查退出代码。 (2认同)

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.