Bash里面的"与"和"或"
First, let’s see some interesting codes. There is a test.sh in the directory, and nothing else.
And”|”,"||”,"&&",“>”,“$?” these symbols can be easily get via google.
When I type these commands, it’s very confused.
$ ls | grep asda && echo $?
$ ls | grep asda || echo $?
1
$ ls | grep test || echo $?
test.sh
$ ls | grep test > /dev/null || echo $?
$ ls | grep test > /dev/null && echo $?
0
$ ls | grep asda > /dev/null && echo $?
$ ls | grep test > /dev/null && echo $?
0
$ ls | grep test > /dev/null && || echo $?
bash: syntax error near unexpected token `||'
$ ls | grep test > /dev/null && echo $? || echo $?
0
$ ls | grep asda > /dev/null && echo $? || echo $?
1
$ ls | grep asda > /dev/null || echo $? && echo $?
1
0
$ ls | grep test > /dev/null || echo $? && echo $?
0
$ ls | grep asda > /dev/null && echo $? || echo $?
1
$ ls | grep test > /dev/null && echo $? || echo $?
0
command_1 || command_2
if command_1 execute successfully, it returns a 0, and command_2 WON’T execute. else, it returns a 1(or other munbers), and command_2 WILL execute.
command_1 && command_2
if command_1 execute successfully, it returns a 0 also, but command_2 WILL execute. else, it returns a 1, but command_2 WON’T execute.
How to define successful or not?
For example, if I have a test.txt in my home directory, and I typed “file test.txt”, it will execute successfully because the file test.txt really exist. But if the command is “file hi.txt”, it won’t execute successfully and will return a 1, because the file command can not find the hi.txt.
Interesting if you combine these commands~