If [ ] or not?


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting If [ ] or not?
# 1  
Old 12-12-2018
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.
# 2  
Old 12-12-2018
[ is a command. These days it's a shell-builtin for performance reasons but standards still require the [ program to exist.

Code:
$ which '['

/usr/bin/[

$

# 3  
Old 12-12-2018
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'
Quote:
if [ "$x" = "valid" ] ; then
can also be written as
Code:
if test $x = "valid" ; then

For example:
Code:
if test $x = "valid" ; then echo ok ; fi

This User Gave Thanks to Ralph For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread
Login or Register to Ask a Question