I wonder if there is a difference between
if [ $x -eq $y -o $x -eq 1 ]
if [ $x -eq $y ] || [ $x -eq 1 ]
Both seem to work.
Thanks
I wonder if there is a difference between
if [ $x -eq $y -o $x -eq 1 ]
if [ $x -eq $y ] || [ $x -eq 1 ]
Both seem to work.
Thanks
TL;DR: they're not the same and the purpose is slightly different, although they aim at same desired effect.
The difference is in who does the logic checks. As you may know, the square brackets are synonymous with test
command. So, with -o
you see single test command, and the two conditions are evaluated together, then returned exit status to bash.
With &&
you have two test
statements, each returning separately, but then bash evaluates if they are both true. The last one is recommended nowadays , since test
is a bit dated and has issues (and new version of test [[
is often recommended, see this), plus it is far more readable since the &&
or ||
are used in many other languages including C and Java.
So in first case, with [
you evaluate two expressions, with &&
you evaluate exit statuses of two [
comands.
Additional info:
As pointed out by @steeldriver in the comments, there is indeed built-in command test
, which is bash's internal implementation of /usr/bin/test
. Regardless of this fact, the way built-in test
and /usr/bin/test
work syntactically is exactly the same.
Keep in mind, however, that if you're using some other shell than bash
or Ubuntu's default shell dash
, then you will likely be using /usr/bin/test
. Korn shell, ksh
for instance, doesn't have test
built-in.
Keep in mind also the fact that &&
and test
are not equivalent:
test
is supposed to evaluate statements and return exit status like any other command (see POSIX specifications for test). It has a whole list of things you can evaluate - existence of files, filetypes, integer and string comparison.&&
and ||
are used by shells to evaluate exit statuses of separate commands just like ;
does, which is one of the reasons in bash man page these operators are under Lists
section. In addition, they cannot be a stand-alone command , like test
- they are standard shell list operators . So, unlike test
you cannot use &&
to check if file exists; you can only know if command to the left exited successfully or with failure, and run or not run second command accordingly.