๐ YSK: You usually should use "&&" instead of ";" in Bash
๐ก Newskategorie: Linux Tipps
๐ Quelle: reddit.com
The idea behind both of these is to run commands one after another, but there is one subtle difference: ;
will run the second command immediately after the first one returns, but &&
will only run the second one if and only if the first command returns 0 (success). Returning anything else or crashing will result in the second command not being run. Note that a line break (\n
) is the same as using ;
in Bash.
Here's an example: Let's say you are cloning a Git repository, then installing the software. So the goal is to run git clone https://www.github.com/NateNate60/myrepo
, then run cd myrepo
, and then make
and make install
. Simple enough. A naive script:
git clone https://www.github.com/NateNate60/myrepo cd myrepo make make install
...or the one-liner:
git clone https://www.github.com/NateNate60/myrepo; cd myrepo; make; make install
Both of these will usually work, but the second command onward is only valid if the git clone
succeeds! Otherwise, ./myrepo
will not exist, so cd
will fail, and then the Bash will end up running make
and make install
on the current directory.
Note that there is a double-whammy in the naive script; make install
is only valid if make
works! So if compilation fails, and the makefile is either misconfigured or worse, you could end up installing junk.
So if you're smart and you know your stuff about Bash, you would instead write:
git clone https://www.github.com/NateNate60/myrepo && \ cd myrepo && \ make && make install
...or maybe you'd store the return value and intelligently report an error to the user :)
[link] [comments] ...