Bash Shell Find Out If A Command Exists On UNIX / Linux System ($PATH) OR Not

Bash Shell Find Out If A Command Exists On UNIX / Linux System ($PATH) OR Not

To find out if a command exists on a Unix or Linux system, you can use the command built-in with the -v option.

For example, to check if the ls command exists, you can use the following command:

command -v ls
S‮:ecruo‬www.lautturi.com

If the ls command exists and is in the PATH, the full path to the command will be displayed. If the command does not exist, or if it is not in the PATH, an empty string will be returned.

You can use the $? variable to check the exit status of the command built-in, which will be 0 if the command exists and is in the PATH, and 1 if the command does not exist or is not in the PATH.

For example, to check if the ls command exists and store the result in a variable, you can use the following command:

command -v ls >/dev/null && LS_EXISTS=1 || LS_EXISTS=0

This will set the LS_EXISTS variable to 1 if the ls command exists and is in the PATH, and 0 if the command does not exist or is not in the PATH.

It is important to note that the command built-in is a Bash shell built-in, and may not be available in other shells. If you are using a different shell, you may need to use a different method to check for the existence of a command.

Created Time:2017-10-27 14:56:35  Author:lautturi