When is 'if' not necessary?

In some scripts, I’ve seen if conditional statements written as:

if [ some_conditional_statement ]; then
    # do stuff


[ some_conditional_statement ] && #do stuff

Is the second example equivalent (do stuff portion will only execute if the conditional is true), but only useful when you only need to perform one command such as:

[ -f "/path/to/some/file" ] && . /path/to/some/file

Or is there another difference I am missing?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The if-clause will execute whatever is in between then and fi if the expression after the if is true, which in shell terms mean that its exit value is zero. You can use a command or the brackets which is just a short form for the test command. The a && b construct means: “evaluate a and if its true also evaluate b”. So your two examples are equivalent, but the if-clause is more readable and can be used to group several commands.

Solution 2

OK, I presume that you understand that [ condition ]
(or [[ condition ]] in bash)
is, essentially, a command that has no side effects,
but that evaluates the condition and gives an appropriate exit status. 
You mentioned chaining &&s together. 
You can do that;

A  &&  B  &&  C

is equivalent to

if A
    if B

But you seem to be asking how to do

if A

You can do that with

A  &&  (B; C)


A  &&  { B; C;}


  • The parentheses give you a subshell; i.e., commands B and C run in a child process. 
    commands like variable assignments or cd will have no effect on the parent shell. 
    Commands in braces run in the same process as the A command.
  • In the brace syntax,
    there must be a space after the { and a ; (or a &) before the }.

My opinion:

I strongly recommend using the ifthenelse syntax, for improved readability.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply