Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash scripting, invoke function as a conditional test

Tags:

bash

scripting

Can someone please tell me why line 7 (if statement) generates an error:

test.sh: line 7: [: command_exists: unary operator expected

thanks!

#!/usr/bin/env bash

command_exists () {
  command -v "$1" &> /dev/null ;
}

if [ ! command_exists ruby ]; then  # test.sh: line 7: [: command_exists: unary operator expected
  echo 'found ruby'
else
  echo 'ruby not found'
fi
like image 731
Xiaotian Guo Avatar asked Sep 28 '26 09:09

Xiaotian Guo


1 Answers

if ! command_exists ruby; then

In Bash, if executes a command and acts on its return value. [ happens to be a command.

like image 196
Dennis Williamson Avatar answered Sep 30 '26 13:09

Dennis Williamson