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
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.
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 .
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.
&>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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With