If [ ] or not?

As far as I can see from all the examples I can find the following is correct:

if [ "$x" = "valid" ]; then

So, if that's how an if has to work, and a command should be within "$(command)" why does the following work:

if pgrep process; then
echo "Yes"
else
echo "No"
fi

I know that returns a number, but you'd check for a number in the first example. I'm fine with it working, that doesn't bother me, I just want to understand why.

Many thanks.

[ is a command. These days it's a shell-builtin for performance reasons but standards still require the [ program to exist.

$ which '['

/usr/bin/[

$

The is not part of the if-statement. if only requires a command (or a list of commands), not necessarily the .
The is a command. It stands for 'test'

can also be written as

if test $x = "valid" ; then

For example:

if test $x = "valid" ; then echo ok ; fi
1 Like