Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Shorter if syntax #112

Open
qiufeihai opened this issue Jan 26, 2021 · 7 comments
Open

Shorter if syntax #112

qiufeihai opened this issue Jan 26, 2021 · 7 comments

Comments

@qiufeihai
Copy link

[[ 1 == 1 ]] && { command exit 1 } || { this command will exec }
how to avoid???

@linux478
Copy link

linux478 commented Dec 9, 2021

I do not understand what you are trying to tell.

@Skizo4
Copy link

Skizo4 commented Dec 10, 2021 via email

@TedHartDavis
Copy link

I am so confused by this.

@TinCanTech
Copy link

Missing terminating quote, bracket or keyword

@terminalforlife
Copy link

terminalforlife commented Dec 24, 2021

I'm sure you found a solution by now, but just in-case you didn't:

You have two syntax errors, because you're missing the ; before the final } in each command group. The typical way to group commands (without a subshell) is { like this; }. Grouping a single command is redundant.

The COMMAND && COMMAND || COMMAND approach does not equate to if, then, else, although it can work in a similar way. Likewise, COMMAND || COMMAND && COMMAND does not equate to the opposite.

Why? Because what the first example actually means is that the 2nd command will execute if the 1st one succeeds, or the 3rd command will execute if the 1st command fails. However, if the 1st command succeeds and the 2nd command also happens to fail, then all three commands wind up being executed regardless. Understanding this is very important, as you can wind up doing some pretty stupid stuff otherwise.

Furthermore, the exit statuses are not contained, unlike with an if statement, which is pretty important if it's the last command in a script or you're checking $?.

@YasserKa
Copy link

YasserKa commented May 9, 2022

"Shorter if syntax" should be removed to stop spreading miss-information.

More context can be found here: http://mywiki.wooledge.org/BashPitfalls#cmd1_.26.26_cmd2_.7C.7C_cmd3

@terminalforlife
Copy link

terminalforlife commented May 9, 2022

Agreed, it's misleading and incorrect. I see what the author meant, but it's important to be accurate when it comes to complicated matters like programming, IMO. Logical operators can be used similar to an if statement, in a simple way, but it's not technically or actually a replacement or "shorter" version.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants