Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check dependency in bash script

Tags:

linux

bash

I want to check whether nodejs is installed on the system or not. I am getting this error:

Error : command not found.

How can i fix it?

#!/bin/bash

if [ nodejs -v ]; then
echo "nodejs found"
else
echo "nodejs not found"
fi
like image 723
Rohit Avatar asked Oct 23 '15 08:10

Rohit


People also ask

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

What is $() in bash?

$() means: "first evaluate this, and then evaluate the rest of the line". Ex : echo $(pwd)/myFile.txt. will be interpreted as echo /my/path/myFile.txt. On the other hand ${} expands a variable.

What is Echo $$ in bash?

The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.


2 Answers

You can use the command bash builtin:

if command -v nodejs >/dev/null 2>&1 ; then
    echo "nodejs found"
    echo "version: $(nodejs -v)"
else
    echo "nodejs not found"
fi
like image 94
hek2mgl Avatar answered Sep 30 '22 17:09

hek2mgl


The name of the command is node, not nodejs

which returns the path to the command to stdout, if it exists

if [ $(which node 2>/dev/null) ]; then
  echo "nodejs found"
else
  echo "nodejs not found"
fi
like image 37
edi9999 Avatar answered Sep 30 '22 18:09

edi9999