0

I am trying to write a script to check to see if more than 1 command is available on my system. I have tried the following and get an error

if [$(test "$(command -v brew)")] && [$(test "$(command -v python)")]; then
  echo -e "This will work"
fi

When I just need to do 1 of them I do

if test "$(command -v brew)"; then
  echo -e "Hi"
fi

What am I doing wrong

jrock2004
  • 3,229
  • 5
  • 40
  • 73
  • 2
    `[` is a **command** (specifically, it's another name for the command `test`). Just as you can't run `ls-l` and need to run `ls -l`, you can't run `[something]`; it needs to be `[ something ]` – Charles Duffy Aug 05 '21 at 03:15
  • 1
    Consider `if command -v brew >/dev/null 2>&1 && command -v python >/dev/null 2>&1; then ...` – Charles Duffy Aug 05 '21 at 03:16
  • 2
    ...the `test "$(command -v brew)"` thing works, but it's really unnecessarily slow for no good reason (`$()` starts a subshell, so it has to fork off a whole new copy of bash). – Charles Duffy Aug 05 '21 at 03:16
  • 1
    ...and `[ test "$(something)" ]` just doesn't make sense -- it's like running `test test "$(something)"`. If you have `[`, you don't need `test`, and the inverse. – Charles Duffy Aug 05 '21 at 03:19
  • I get an error too: `[]: command not found`. You have insufficient white space after `[` and before `]`. But that's not the only problem. – Jeff Holt Aug 05 '21 at 03:24
  • BTW, I might write a function like `all_cmds_exist() { for arg; do command -v "$arg" >/dev/null 2>&1 || return; done; return 0; }` to be able to write `if all_cmds_exist brew python; then ...` – Charles Duffy Aug 05 '21 at 03:27
  • @jrock2004: If you need two of them, don't add the funny brackets. After all, `[` is basically the same program as `test`. Just do a `if test "$(command -v brew)" && test "$(command -v python)"`. – user1934428 Aug 05 '21 at 07:39

1 Answers1

0
if [ "$(command -v ls)" ] && [ "$(command -v python)" ]; then
  echo "This will work"
fi
klbjlabs
  • 54
  • 3
  • 4
    Don't encourage unnecessary use of `echo -e`. It's nonstandard, nonportable, and doesn't always even work (see https://replit.com/@CharlesDuffy2/OrangeAbandonedGreyware#main.sh for an example of that, demonstrating why someone's answer using `echo -e` to write a two-byte file was unreliable). More on that at https://unix.stackexchange.com/a/65819/3113 – Charles Duffy Aug 05 '21 at 03:20