0

I googled many solutions but did not find one that fully worked. My own rough working is:

[ $(which curl) -eq "" ] || sudo apt install curl

This doesn't quite work, saying "unary operator expected". I've tried = or ==, so I'm not getting how to do a test like this. Is it possible that the empty output from which curl is a $null and I have to test for that?

Alternatively, is there a way to just run sudo apt install curl and then 2>&null at the end to suppress if it's already installed?

YorSubs
  • 3,194
  • 7
  • 37
  • 60
  • The trivial fix is to quote the command substitution. Sure you can run `sudo apt -y install curl >/dev/null 2>&1` but that is going to fail or hang if the user does not have their `sudo` password cached. – tripleee Nov 26 '20 at 13:14
  • @YorSubs : Technically speaking, you don't test whether an executable `curl` exists, you just test whether it exists **and is in your PATH**. Also, you don't know whether (whatever is hidden behind the name _curl_) is that curl in that version you need. One alternative would be to run `curl --version` and parse its output. – user1934428 Nov 26 '20 at 13:17
  • I see your point. Would testing for `/usr/bin/curl` be more rigorous (I don't need completely bulletproof, and it would be very odd for someone to put a file there that was not a downloaded version of `curl`). My only question then is: do different distros put `curl` in different places, or would `/usr/bin/curl` be a reliable cross-platform location? – YorSubs Nov 26 '20 at 13:23
  • Not only can other distros put curl elsewhere, they can also use a different installer than apt. – choroba Nov 26 '20 at 15:21

1 Answers1

5

which returns a failure if it doesn't find the program, so you can

which curl &> /dev/null || sudo apt install curl

Note that if someone has a different program in $PATH named curl, the script can still fail later.

-eq compares numbers, not strings.

choroba
  • 231,213
  • 25
  • 204
  • 289