DEV Community

Discussion on: Run multiple commands in one line with `;`, `&&` and `||` - Linux Tips

Collapse
 
thefluxapex profile image
Ian Pride • Edited

Ternary (or more) operations on a single line:

[[ 1 -eq 1 ]] && echo true || echo false

[[ "${var}" == "string" ]] && ([[ "$(id -un)" == "root" ]] && echo ROOT || echo USER) || echo false
Enter fullscreen mode Exit fullscreen mode

And can be multiple lines:

[[ 1 -eq 1 ]] &&
echo true ||
echo false

[[ "${var}" == "string" ]] &&
([[ "$(id -un)" == "root" ]] &&
    echo ROOT ||
    echo USER) ||
echo false
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bitecode profile image
BC

Nice 👍 thanks for the add-up, Ian

Collapse
 
thefluxapex profile image
Ian Pride

You're welcome; I just thought it would add a little perspective of how this concept can be used in various ways. Some might always prefer to use if/else statements to be safe & sometimes it is necessary, but I find myself using this type of 'shortcut' more times than not when it's safe to use.

Collapse
 
ferricoxide profile image
Thomas H Jones II

I use the <CMD> && <SUCCESS_ACTION> || <FAIL_ACTION> method quite a lot ...annoying that BASH-linters complain about it.

Collapse
 
chaitanyashahare profile image
Chaitanya Shahare

Thanks for these examples, they are really helpful