Wednesday, May 15, 2024
10
rated 0 times [  10] [ 0]  / answers: 1 / hits: 845  / 2 Years ago, thu, september 8, 2022, 5:18:20

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


More From » command-line

 Answers
3

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.

  • Logic operators such as && 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.


[#13053] Friday, September 9, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deringach

Total Points: 412
Total Questions: 107
Total Answers: 101

Location: Palestine
Member since Tue, Jul 20, 2021
3 Years ago
;