How to check if command exists in a shell script?

I am writing my first shell script. In my script I would like to check if a certain command exists, and if not, install the executable. How would I check if this command exists?

if #check that foobar command doesnt exist
then
    #now install foobar
fi

In general, that depends on your shell, but if you use bash, zsh, ksh or sh (as provided by dash), the following should work:

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

For a real installation script, you'd probably want to be sure that type doesn't return successfully in the case when there is an alias foobar . In bash you could do something like this:

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

try using type :

type foobar

For example:

$ type ls
ls is aliased to `ls --color=auto'

$ type foobar
-bash: type: foobar: not found

This is preferable to which for a few reasons:

1) the default which implementations only support the -a option that shows all options, so you have to find an alternative version to support aliases

2) type will tell you exactly what you are looking at (be it a bash function or an alias or a proper binary).

3) type doesn't require a subprocess

4) type cannot be masked by a binary (for example, on a linux box, if you create a program called which which appears in path before the real which , things hit the fan. type , on the other hand, is a shell built-in [yes, a subordinate inadvertently did this once]


Check if a program exists from a Bash script covers this very well. In any shell script, you're best off running command -v $command_name for testing if $command_name can be run. In bash you can use hash $command_name , which also hashes the result of any path lookup, or type -P $binary_name if you only want to see binaries (not functions etc.)

链接地址: http://www.djcxy.com/p/57056.html

上一篇: 干净的方式从shell脚本启动Web浏览器?

下一篇: 如何检查命令是否存在于shell脚本中?