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 03:01

In case you want to check if a program exists and is really a program, not a bash built-in command, then command, type and hash are not appropriate for testing as they all return 0 exit status for built-in commands.

For example, there is the time program which offers more features than the time built-in command. To check if the program exists, I would suggest using which as in the following example:

# first check if the time program exists
timeProg=`which time`
if [ "$timeProg" = "" ]
then
  echo "The time program does not exist on this system."
  exit 1
fi

# invoke the time program
$timeProg --quiet -o result.txt -f "%S %U + p" du -sk ~
echo "Total CPU time: `dc -f result.txt` seconds"
rm result.txt
查看更多
素衣白纱
3楼-- · 2018-12-31 03:01
checkexists() {
    while [ -n "$1" ]; do
        [ -n "$(which "$1")" ] || echo "$1": command not found
        shift
    done
}
查看更多
公子世无双
4楼-- · 2018-12-31 03:03

The hash-variant has one pitfall: On the command line you can for example type in

one_folder/process

to have process executed. For this the parent folder of one_folder must be in $PATH. But when you try to hash this command, it will always succeed:

hash one_folder/process; echo $? # will always output '0'
查看更多
听够珍惜
5楼-- · 2018-12-31 03:03

It will tell according to the location if the program exist or not

if [ -x /usr/bin/yum ]; then
    echo This is Centos
fi
查看更多
看风景的人
6楼-- · 2018-12-31 03:05

hash foo 2>/dev/null: works with zsh, bash, dash and ash.

type -p foo: it appears to work with zsh, bash and ash (busybox), but not dash (it interprets -p as an argument).

command -v foo: works with zsh, bash, dash, but not ash (busybox) (-ash: command: not found).

Also note that builtin is not available with ash and dash.

查看更多
笑指拈花
7楼-- · 2018-12-31 03:07

Try using:

test -x filename

or

[ -x filename ]

From the bash manpage under Conditional Expressions:

 -x file
          True if file exists and is executable.
查看更多
登录 后发表回答