Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a command exists in a shell script? [duplicate]

Tags:

shell

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
like image 923
Andrew Avatar asked Oct 04 '22 21:10

Andrew


People also ask

How will you check whether a command exists in Linux?

The -P option force a PATH search for each COMMAND NAME, even if it is an alias, builtin, or function, and returns the name of the disk file that would be executed.

How can I check if a program exists from a bash script?

You can use the posix compatible command to check, if the command exists from a bash script or not. if it returns >0 when the command is not found or an error occurs. similary you can use type and hash .

How do you check if a shell script is already running?

From Shell Every running process has a PID. We use pidof command to determine the PID of our shell script. If the PID exists, it means the shell script is already running. In such cases, the above script will display a message saying that the process is already running.

What does &> mean in bash?

&>word (and >&word redirects both stdout and stderr to the result of the expansion of word. In the cases above that is the file 1 . 2>&1 redirects stderr (fd 2) to the current value of stdout (fd 1).


1 Answers

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
like image 54
Ivan Tarasov Avatar answered Oct 18 '22 09:10

Ivan Tarasov