loading...

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

0xbf profile image Bo ・1 min read

There are 3 ways to run multiple shell commands in one line:

1) Use ;

No matter the first command cmd1 run successfully or not, always run the second command cmd2:

# cmd1; cmd2
$ cd myfolder; ls   # no matter cd to myfolder successfully, run ls

2) Use &&

Only when the first command cmd1 run successfully, run the second command cmd2:

# cmd1 && cmd2
$ cd myfolder && ls  # run ls only after cd to myfolder

3) Use ||

Only when the first command cmd1 failed to run, run the second command cmd2:

# cmd1 || cmd2
$ cd myfolder || ls  # if failed cd to myfolder, `ls` will run

Discussion

pic
Editor guide
 

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

And can be multiple lines:

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

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

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

 
0xbf profile image Bo github logo Author

Nice 👍 thanks for the add-up, Ian

 

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.

 
 

this is extra cool ! Most of the time I use &&, I will try to use other syntaxes.

 

Can this be nested?

A && (B && echo passed || echo B failed ) || echo A failed