Pablitoo Menii Pablitoo Menii - 4 months ago 15
Linux Question

NodeJs installed but cant execute it. Messed it up with bash script

I'm learning bash scripting and was trying to write a script that checks if nodeJs is installed, and if it is not, then install it.

NodeJs is installed in my system. Before messing it up, the output I got when executing

node -v
was v4.x.x.

Then, I was following this post and I wrote the following code in my script:

#!/bin/bash
if [ command -v node >/usr/bin/node 2>&1 ]; then
# save node version in a string variable.
STRING=cat | node -v

echo "NodeJs version: " ${STRING}
else
echo "NodeJs not found."
fi


I executed my script (testScript.sh) but now when I run
node -v
the output I get is:

/usr/bin/node: line 1: ./testScript.sh:: No such file or directory


I cant figure out what I broke... any ideas? Thanks a lot.

Answer

In your script, you are trying to redirect the output of command -v node to the file /usr/bin/node. That's not what you want. The script should be:

#!/bin/bash
if [ command -v node >/dev/null 2>&1 ]; then
    # save node version in a string variable.
    STRING=cat | node -v

    echo "NodeJs version: " ${STRING}
else
    echo "NodeJs not found."
fi

Read more about /dev/null here: http://man7.org/linux/man-pages/man4/null.4.html

It seems you have already overwritten the binary file /usr/bin/node with the content of the command command -v node. Look at the output for the command: file /usr/bin/node. It should be an ELF file. If you have ASCII text in the output, then you have indeed replaced the binary.

Comments