0

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.

Community
  • 1
  • 1
Pablo Meni
  • 87
  • 9

1 Answers1

1

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.

Nehal J Wani
  • 16,071
  • 3
  • 64
  • 89
  • Thanks for your fast answer. Now I modified the script and ran it. But I still can't run `node -v`. It keeps giving me the same strange output. Did I modified something when running the wrong version of the script? (the one with /usr/bin/node). Thanks! – Pablo Meni Aug 04 '16 at 15:42
  • 1
    @PablitooMenii Yes, you did. You will have to reinstall node. – Nehal J Wani Aug 04 '16 at 15:43
  • 1
    @PablitooMenii: Yes, you did modify something. You deleted the node executable and replaced it with the output from your script. That's what `command -v node >/usr/bin/node` means. – slebetman Aug 04 '16 at 15:43
  • 1
    @PablitooMenii: Be very careful of the `>` operator. `> somefile` means delete the contents of somefile and write this output to it. – slebetman Aug 04 '16 at 15:45
  • Got it, Thanks to both of you! – Pablo Meni Aug 04 '16 at 15:47