How to check if a program exists from a Bash scrip

2018-12-31 02:39发布

How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script?

It seems like it should be easy, but it's been stumping me.

标签: bash
30条回答
忆尘夕之涩
2楼-- · 2018-12-31 02:51

I never did get the above solutions to work on the box I have access to. For one, type has been installed (doing what more does). So the builtin directive is needed. This command works for me:

if [ `builtin type -p vim` ]; then echo "TRUE"; else echo "FALSE"; fi
查看更多
妖精总统
3楼-- · 2018-12-31 02:51

To mimic Bash's type -P cmd we can use POSIX compliant env -i type cmd 1>/dev/null 2>&1.

man env
# "The option '-i' causes env to completely ignore the environment it inherits."
# In other words, there are no aliases or functions to be looked up by the type command.

ls() { echo 'Hello, world!'; }

ls
type ls
env -i type ls

cmd=ls
cmd=lsx
env -i type $cmd 1>/dev/null 2>&1 || { echo "$cmd not found"; exit 1; }
查看更多
不流泪的眼
4楼-- · 2018-12-31 02:53

If you guys can't get the things above/below to work and pulling hair out of your back, try to run the same command using bash -c. Just look at this somnambular delirium, this is what really happening when you run $(sub-command):

First. It can give you completely different output.

$ command -v ls
alias ls='ls --color=auto'
$ bash -c "command -v ls"
/bin/ls

Second. It can give you no output at all.

$ command -v nvm
nvm
$ bash -c "command -v nvm"
$ bash -c "nvm --help"
bash: nvm: command not found
查看更多
柔情千种
5楼-- · 2018-12-31 02:54

I had to check if git was installed as part of deploying our CI server. My final bash script was as follows (Ubuntu server):

if ! builtin type -p git &>/dev/null; then
  sudo apt-get -y install git-core
fi

Hope this help someone else!

查看更多
大哥的爱人
6楼-- · 2018-12-31 02:55

The following is a portable way to check whether a command exists in $PATH and is executable:

[ -x "$(command -v foo)" ]

Example:

if ! [ -x "$(command -v git)" ]; then
  echo 'Error: git is not installed.' >&2
  exit 1
fi

The executable check is needed because bash returns a non-executable file if no executable file with that name is found in $PATH.

Also note that if a non-executable file with the same name as the executable exists earlier in $PATH, dash returns the former, even though the latter would be executed. This is a bug and is in violation of the POSIX standard. [Bug report] [Standard]

In addition, this will fail if the command you are looking for has been defined as an alias.

查看更多
旧人旧事旧时光
7楼-- · 2018-12-31 02:55

command -v works fine if POSIX_BUILTINS option is set for the <command> to test for but can fail if not. (it has worked for me for years but recently ran into one where it didn't work).

I find the following to be more fail-proof:

test -x $(which <command>)

Since it tests for 3 things: path, execution and permission.

查看更多
登录 后发表回答