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.
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.
POSIX compatible:
command -v <the_command>
For bash
specific environments:
hash <the_command> # For regular commands. Or...
type <the_command> # To check built-ins and keywords
Avoid which
. Not only is it an external process you're launching for doing very little (meaning builtins like hash
, type
or command
are way cheaper), you can also rely on the builtins to actually do what you want, while the effects of external commands can easily vary from system to system.
Why care?
which
that doesn't even set an exit status, meaning the if which foo
won't even work there and will always report that foo
exists, even if it doesn't (note that some POSIX shells appear to do this for hash
too).which
do custom and evil stuff like change the output or even hook into the package manager.So, don't use which
. Instead use one of these:
$ command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
$ type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
$ hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
(Minor side-note: some will suggest 2>&-
is the same 2>/dev/null
but shorter – this is untrue. 2>&-
closes FD 2 which causes an error in the program when it tries to write to stderr, which is very different from successfully writing to it and discarding the output (and dangerous!))
If your hash bang is /bin/sh
then you should care about what POSIX says. type
and hash
's exit codes aren't terribly well defined by POSIX, and hash
is seen to exit successfully when the command doesn't exist (haven't seen this with type
yet). command
's exit status is well defined by POSIX, so that one is probably the safest to use.
If your script uses bash
though, POSIX rules don't really matter anymore and both type
and hash
become perfectly safe to use. type
now has a -P
to search just the PATH
and hash
has the side-effect that the command's location will be hashed (for faster lookup next time you use it), which is usually a good thing since you probably check for its existence in order to actually use it.
As a simple example, here's a function that runs gdate
if it exists, otherwise date
:
gnudate() {
if hash gdate 2>/dev/null; then
gdate "$@"
else
date "$@"
fi
}
2>&-
("close output file descriptor 2", which is stderr) has the same result as 2> /dev/null
; 2) >&2
is a shortcut for 1>&2
, which you may recognize as "redirect stdout to stderr". See the Advanced Bash Scripting Guide i/o redirection page for more info.
– mikewaters
Dec 21 '11 at 19:48
while read element ; do .. done <<< $(echo ${ArrayVar[*]})
, for word in $(fgrep -l $ORIGINAL *.txt)
, ls -l "$directory" | sed 1d
, {{for a in seq $BEGIN $END
}}, ... Many have tried to contact the authors and propose improvements but it's no wiki and requests have landed on deaf ears.
– lhunath
Jun 12 '13 at 20:00
2>&-
is not the same as 2>/dev/null
. The former closes the file descriptor, while the latter simply redirects it to /dev/null
. You may not see an error because the program tries to inform you on stderr that stderr is closed.
– nyuszika7h
Nov 5 '14 at 14:36
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.
command -v
produce a path even for a non-executable file? That is, the -x really necessary?
– einpoklum - reinstate Monica
Oct 26 '17 at 10:14
-x
tests that the file is executable, which is what the question was.
– Ken Sharp
Oct 26 '17 at 13:03
command
will itself test for its being executable - won't it?
– einpoklum - reinstate Monica
Oct 26 '17 at 13:04
$PATH
when executing a command. However, the behavior of command -v
is very inconsistent. In dash, it returns the first matching file in $PATH
, regardless of whether it's executable or not. In bash, it returns the first executable match in $PATH
, but if there's none, it can return a non-executable file. And in zsh, it will never return a non-executable file.
– nyuszika7h
Oct 26 '17 at 13:52
dash
is the only one out of those three that's non-POSIX-compliant; [ -x "$(command -v COMMANDNAME)"]
will work in the other two. Looks like this bug has already been reported but hasn't got any responses yet: bugs.debian.org/cgi-bin/bugreport.cgi?bug=874264
– nyuszika7h
Oct 26 '17 at 14:12
I agree with lhunath to discourage use of which
, and his solution is perfectly valid for BASH users. However, to be more portable, command -v
shall be used instead:
$ command -v foo >/dev/null 2>&1 || { echo "I require foo but it's not installed. Aborting." >&2; exit 1; }
Command command
is POSIX compliant, see here for its specification: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/command.html
Note: type
is POSIX compliant, but type -P
is not.
&>/dev/null
. However, I agree with you, what really matters is portability, I've edited my answer accordingly, now using standard sh redirect >/dev/null 2>&1
.
– GregV
Mar 5 '12 at 10:58
I have a function defined in my .bashrc that makes this easier.
command_exists () {
type "$1" &> /dev/null ;
}
Here's an example of how it's used (from my .bash_profile
.)
if command_exists mvim ; then
export VISUAL="mvim --nofork"
fi
&>
may not be available in your version of Bash. Marcello's code should work fine; it does the same thing.
– Josh Strater
Aug 2 '16 at 1:28
then
for instance. See this answer if you require the executable to exist in $PATH
.
– Tom Hale
Dec 16 '18 at 2:14
It depends whether you want to know whether it exists in one of the directories in the $PATH
variable or whether you know the absolute location of it. If you want to know if it is in the $PATH
variable, use
if which programname >/dev/null; then
echo exists
else
echo does not exist
fi
otherwise use
if [ -x /path/to/programname ]; then
echo exists
else
echo does not exist
fi
The redirection to /dev/null/
in the first example suppresses the output of the which
program.
Expanding on @lhunath's and @GregV's answers, here's the code for the people who want to easily put that check inside an if
statement:
exists()
{
command -v "$1" >/dev/null 2>&1
}
Here's how to use it:
if exists bash; then
echo 'Bash exists!'
else
echo 'Your system does not have Bash'
fi
man bash
and learn how to use it. It will make your code much simpler and more elegant. The brackets are not a part of if
syntax, they are just a shorthand for the command test
. if
examines, whether the command succeeded (has the exit status of 0).
– Palec
Dec 8 '15 at 8:09
command
succeeds even for aliases, which might be somewhat counterintuitive. Checking for existence in an interactive shell will give different results from when you move it to a script.
– Palec
Dec 12 '15 at 9:23
shopt -u expand_aliases
ignores/hides aliases (like the alias ls='ls -F'
mentioned in another answer) and shopt -s expand_aliases
resolves them via command -v
. So perhaps it should be set prior to the check and unset after, though it could affect the function return value if you don't capture and return the output of the command call explicitly.
– dragon788
Jul 2 '17 at 3:13
Try using:
test -x filename
or
[ -x filename ]
From the bash manpage under Conditional Expressions:
-x file True if file exists and is executable.
To use hash
, as @lhunath suggests, in a bash script:
hash foo &> /dev/null
if [ $? -eq 1 ]; then
echo >&2 "foo not found."
fi
This script runs hash
and then checks if the exit code of the most recent command, the value stored in $?
, is equal to 1
. If hash
doesn't find foo
, the exit code will be 1
. If foo
is present, the exit code will be 0
.
&> /dev/null
redirects standard error and standard output from hash
so that it doesn't appear onscreen and echo >&2
writes the message to standard error.
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
if
syntax, simply use if builtin type -p vim; then ...
. And the backticks are really ancient and deprecated syntax, $()
is supported even by sh
on all modern systems.
– nyuszika7h
Feb 2 '17 at 14:42
Check for multiple dependencies and inform status to end users
for cmd in latex pandoc; do
printf '%-10s' "$cmd"
if hash "$cmd" 2>/dev/null; then
echo OK
else
echo missing
fi
done
Sample output:
latex OK
pandoc missing
Adjust the 10
to the maximum command length. Not automatic because I don't see a non verbose POSIX way to do it:
How to align the columns of a space separated table in Bash?
column -t
(part of util-linux).
– Patrice Levesque
Feb 22 '15 at 18:15
If you check for program existence, you are probably going to run it later anyway. Why not try to run it in the first place?
if foo --version >/dev/null 2>&1; then
echo Found
else
echo Not found
fi
It's a more trustworthy check that the program runs than merely looking at PATH directories and file permissions.
Plus you can get some useful result from your program, such as its version.
Of course the drawbacks are that some programs can be heavy to start and some don't have a --version
option to immediately (and successfully) exit.
git
is installed. It's very fast. True that not all commands do this fast and not all have that flag; good for mentioning that.
– Wildcard
Jan 1 '16 at 2:53
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
.
Why not use Bash builtins if you can?
which programname
...
type -P programname
-P
isn't POSIX. Why is type -P
preferred?
– mikemaccana
Jan 2 '18 at 18:24
For those interested, none of the methodologies above work if you wish to detect an installed library. I imagine you are left either with physically checking the path (potentially for header files and such), or something like this (if you are on a Debian-based distro):
dpkg --status libdb-dev | grep -q not-installed
if [ $? -eq 0 ]; then
apt-get install libdb-dev
fi
As you can see from the above, a "0" answer from the query means the package is not installed. This is a function of "grep" - a "0" means a match was found, a "1" means no match was found.
The which
command might be useful. man which
It returns 0 if the executable is found, 1 if it's not found or not executable:
NAME
which - locate a command
SYNOPSIS
which [-a] filename ...
DESCRIPTION
which returns the pathnames of the files which would be executed in the
current environment, had its arguments been given as commands in a
strictly POSIX-conformant shell. It does this by searching the PATH
for executable files matching the names of the arguments.
OPTIONS
-a print all matching pathnames of each argument
EXIT STATUS
0 if all specified commands are found and executable
1 if one or more specified commands is nonexistent or not exe-
cutable
2 if an invalid option is specified
Nice thing about which is that it figures out if the executable is available in the environment that which is run in - saves a few problems...
-Adam
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
.bashrc
have a [ -z "$PS1" ] && return
prepended by # If not running interactively, don't do anything
so I guess that is a reason why even explicit sourcing of bashrc in non-interactive mode doesn't help. The problem can be workarounded by calling a script with a ss64.com/bash/source.html dot operator . ./script.sh
but that is not a thing one would like to remember to type each time.
– user619271
Aug 26 '15 at 12:16
I'd say there's no portable and 100% reliable way due to dangling alias
es. For example:
alias john='ls --color'
alias paul='george -F'
alias george='ls -h'
alias ringo=/
Of course only the last one is problematic (no offence to Ringo!) But all of them are valid alias
es from the point of view of command -v
.
In order to reject dangling ones like ringo
, we have to parse the output of the shell built-in alias
command and recurse into them (command -v
is no superior to alias
here.) There's no portable solution for it, and even a Bash-specific solution is rather tedious.
Note that solution like this will unconditionally reject alias ls='ls -F'
test() { command -v $1 | grep -qv alias }
shopt -u expand_aliases
ignores/hides these aliases and shopt -s expand_aliases
shows them via command -v
.
– dragon788
Jul 2 '17 at 3:07
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!
sudo
: without the conditional, it would always stop and ask for password (unless you did a sudo recently). BTW, it may be useful to do sudo -p "Type your password to install missing git-core: "
so the prompt doesn't come out of the blue.
– Beni Cherniavsky-Paskin
Nov 15 '12 at 12:33
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; }
type
seems to be a builtin
in most shells so this can't work because env
uses execvp
to run command
so command
cannot be a builtin
(and the builtin
will always be run within the same environment). This fails for me in bash
, ksh93
, zsh
, busybox [a]sh
and dash
all of which provide type
as a shell builtin.
– Adrian Frühwirth
Apr 17 '14 at 9:00
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'
$PATH
"—This is completely inaccurate. Try it. For this to work, one_folder must be in the current directory.
– Wildcard
Jan 1 '16 at 2:55
I second the use of "command -v". E.g. like this:
md=$(command -v mkdirhier) ; alias md=${md:=mkdir} # bash
emacs="$(command -v emacs) -nw" || emacs=nano
alias e=$emacs
[[ -z $(command -v jed) ]] && alias jed=$emacs
If there is no external type
command available (as taken for granted here), we can use POSIX compliant env -i sh -c 'type cmd 1>/dev/null 2>&1'
:
# portable version of Bash's type -P cmd (without output on stdout)
typep() {
command -p env -i PATH="$PATH" sh -c '
export LC_ALL=C LANG=C
cmd="$1"
cmd="`type "$cmd" 2>/dev/null || { echo "error: command $cmd not found; exiting ..." 1>&2; exit 1; }`"
[ $? != 0 ] && exit 1
case "$cmd" in
*\ /*) exit 0;;
*) printf "%s\n" "error: $cmd" 1>&2; exit 1;;
esac
' _ "$1" || exit 1
}
# get your standard $PATH value
#PATH="$(command -p getconf PATH)"
typep ls
typep builtin
typep ls-temp
At least on Mac OS X 10.6.8 using Bash 4.2.24(2) command -v ls
does not match a moved /bin/ls-temp
.
my setup for a debian server. i had a the problem when multiple packages contains the same name. for example apache2. so this was my solution.
function _apt_install() {
apt-get install -y $1 > /dev/null
}
function _apt_install_norecommends() {
apt-get install -y --no-install-recommends $1 > /dev/null
}
function _apt_available() {
if [ `apt-cache search $1 | grep -o "$1" | uniq | wc -l` = "1" ]; then
echo "Package is available : $1"
PACKAGE_INSTALL="1"
else
echo "Package $1 is NOT available for install"
echo "We can not continue without this package..."
echo "Exitting now.."
exit 0
fi
}
function _package_install {
_apt_available $1
if [ "${PACKAGE_INSTALL}" = "1" ]; then
if [ "$(dpkg-query -l $1 | tail -n1 | cut -c1-2)" = "ii" ]; then
echo "package is already_installed: $1"
else
echo "installing package : $1, please wait.."
_apt_install $1
sleep 0.5
fi
fi
}
function _package_install_no_recommends {
_apt_available $1
if [ "${PACKAGE_INSTALL}" = "1" ]; then
if [ "$(dpkg-query -l $1 | tail -n1 | cut -c1-2)" = "ii" ]; then
echo "package is already_installed: $1"
else
echo "installing package : $1, please wait.."
_apt_install_norecommends $1
sleep 0.5
fi
fi
}
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
There's a ton of options here but I was surprised no quick one-liners, this is what I used at the beginning of my scripts:
[[ "$(command -v mvn)" ]] || { echo "mvn is not installed" 1>&2 ; exit 1; }
[[ "$(command -v java)" ]] || { echo "java is not installed" 1>&2 ; exit 1; }
this is based on the selected answer here and another source (and me playing around a little).
hope this will be handy for others.
It will tell according to the location if the program exist or not
if [ -x /usr/bin/yum ]; then
echo This is Centos
fi
Assuming you are already following safe shell practices: https://sipb.mit.edu/doc/safe-shell/
set -eu -o pipefail
shopt -s failglob
./dummy --version 2>&1 >/dev/null
This assumes the command can be invoked in such a way that it does (almost) nothing, like reporting its version or showing help.
If the dummy
command is not found bash exits with the following error...
./my-script: line 8: dummy: command not found
This is more useful and less verbose than the other command -v
(and similar) answers because the error message is auto generated and also contains a relevant line number.
dummy
's existence is out of hands of the script's author. Also, it lacks explanation of how it works and that it changes settings of the execution environment.
– Palec
Oct 28 at 6:58
shopt
call can be replaced with POSIX set -f
, which is shorter and portable. The pipefail option is not supported in POSIX, though, and there is no alternative, AFAIK.
– Palec
Oct 28 at 6:59
I use this because it's very easy:
if [ `LANG=C type example 2>/dev/null|wc -l` = 1 ];then echo exists;else echo "not exists";fi
or
if [ `LANG=C type example 2>/dev/null|wc -l` = 1 ];then
echo exists
else echo "not exists"
fi
It uses shell builtin and program echo status to stdout and nothing to stderr by the other hand if a command is not found, it echos status only to stderr.
Script
#!/bin/bash
# Commands found in the hash table are checked for existence before being
# executed and non-existence forces a normal PATH search.
shopt -s checkhash
function exists() {
local mycomm=$1; shift || return 1
hash $mycomm 2>/dev/null || \
printf "\xe2\x9c\x98 [ABRT]: $mycomm: command does not exist\n"; return 1;
}
readonly -f exists
exists notacmd
exists bash
hash
bash -c 'printf "Fin.\n"'
Result
✘ [ABRT]: notacmd: command does not exist
hits command
0 /usr/bin/bash
Fin.
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, existence and execution permission.
test -x $(which ls)
returns 0, as does test -x $(which sudo)
, even though ls
is installed and runnable and sudo
is not even installed within the docker container I'm running in.
– algal
Feb 20 at 2:26
ls
is aliased? I dont think it would work if the command has parameter.
– AnthonyC
Apr 2 at 15:38
which
returns true for these.type
without arguments will additionally return true for reserved words and shell builtins. If "program" means "excutable in$PATH
", then see this answer. – Tom Hale Dec 16 '18 at 2:12